python - Python - 使用 PyGithub 将文件直接上传到 github
问题描述
我有一个公共仓库,想使用 python(PyGithub 库)将文件上传到该仓库。
我从SO引用了以下代码:
import base64
from github import Github
from github import InputGitTreeElement
user = "GithubUsername"
password = "*********"
g = Github(user,password)
repo = g.get_user().get_repo('git-test')
file_list = [
'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\index.html',
'C:\\Users\jesse\Dropbox\Swell-Forecast\git-test\margin_table.html'
]
file_names = [
'index.html',
'margin_table.html'
]
commit_message = 'python update 2'
master_ref = repo.get_git_ref('heads/master')
master_sha = master_ref.object.sha
base_tree = repo.get_git_tree(master_sha)
element_list = list()
for i, entry in enumerate(file_list):
with open(entry) as input_file:
data = input_file.read()
if entry.endswith('.png'):
data = base64.b64encode(data)
element = InputGitTreeElement(file_names[i], '100644', 'blob', data)
element_list.append(element)
tree = repo.create_git_tree(element_list, base_tree)
parent = repo.get_git_commit(master_sha)
commit = repo.create_git_commit(commit_message, tree, [parent])
master_ref.edit(commit.sha)
但我不想克隆仓库,添加文件然后提交。相反,只需直接上传文件。
是否有任何方法/示例代码可用于直接上传?
例如:
当前回购:
file1.txt
file2.txt
上传新文件:
file1.txt
file2.txt
myfolder/
|_ file3.txt
|_ file4.txt
解决方案
我为此创建了一小部分代码。它奏效了。在这里分享它,以便其他人可以从中受益。
示例代码:
此代码将上传文件/替换现有文件。
本地文件路径:/tmp/file.txt
Github 文件夹名称:folder1/
from github import Github
g = Github("username", "password")
repo = g.get_user().get_repo(GITHUB_REPO)
all_files = []
contents = repo.get_contents("")
while contents:
file_content = contents.pop(0)
if file_content.type == "dir":
contents.extend(repo.get_contents(file_content.path))
else:
file = file_content
all_files.append(str(file).replace('ContentFile(path="','').replace('")',''))
with open('/tmp/file.txt', 'r') as file:
content = file.read()
# Upload to github
git_prefix = 'folder1/'
git_file = git_prefix + 'file.txt'
if git_file in all_files:
contents = repo.get_contents(git_file)
repo.update_file(contents.path, "committing files", content, contents.sha, branch="master")
print(git_file + ' UPDATED')
else:
repo.create_file(git_file, "committing files", content, branch="master")
print(git_file + ' CREATED')
这个问题也与此有关。
推荐阅读
- deno - 如何使 typedoc 与 deno 一起使用
- typescript - 如何使用 TypeScript 在 Nuxt 中定义和使用我自己的自定义服务?
- javascript - 在流星自动完成中预选/默认值
- json - 在 swift 中使用 UUID() 和 json
- c# - 如何在不回收 IIS 应用程序池的情况下解决“ORA-06508:PL/SQL:找不到正在调用的程序单元”
- nuxt.js - Nuxt 是否有办法在旧浏览器上向用户显示带有浏览器升级说明的页面,而不是主 Web 应用程序?
- java - 我想检查时间间隔
- vba - Sendkeys 无法输入到正确的应用程序中
- php - 为 php7 安装并行
- c# - 即使在使用 Moq 设置时发送正确数量的参数时也会出现 System.ArgumentException