python - 创建/更新 .json 文件到 GitHub Private Repository,无需使用 Python 创建本地工作目录或克隆 repo
问题描述
我有一个 GitHub Private Repository,它的父目录上有 3 个 .json 文件。假设三个json文件是:
1.json
2.json
3.json
我正在尝试编写一个函数,通过该函数我可以通过带有内容的python函数推送任何一个.json文件,它会提交并推送更改。
我尝试使用此解决方案,但它似乎已过时或不受支持:Python update files on Github remote repo without local working directory
函数应该是这样的:
def update_file_to_repo(file_name,file_content):
# Do the push..
file_name 将 1.json 或任何其他文件名作为字符串,而 file_content 将内容作为我在 main 函数中通过 json.dumps() 导入的字符串。
解决方案
虽然我没有找到任何方法可以在不克隆本地目录中的 repo 的情况下做到这一点
但是,如果您想在使用本地目录时执行以下操作,可以使用以下方法:
将私有仓库克隆到本地目录的功能。您还需要创建个人访问令牌(您可以在此处创建)并确保授予 repo 权限以进行克隆和更改私有 repo。
def initialize_repo():
os.system("git config --global user.name \"your.username\"")
os.system("git config --global user.email \"your_github_email_here\"")
os.system(r"git clone https://username:token@github.com/username/repo.git folder-name")
拉取回购的功能:
def pull_repo():
os.system(r"cd /app/folder-name/ && git pull origin master")
return
推送repo的功能:
def push(pull="no"):
PATH_OF_GIT_REPO = r'/app/folder-name/.git' # make sure .git folder is properly configured
COMMIT_MESSAGE = 'commit done by python script'
# try:
repo = Repo(PATH_OF_GIT_REPO)
if pull=="yes":
pull_repo()
repo.git.add(update=True)
repo.index.commit(COMMIT_MESSAGE)
origin = repo.remote(name='origin')
origin.push()
# except:
# print('Some error occured while pushing the code')
return
现在使用这些函数,只需进行拉取,然后对 json 或您想要的任何其他文件进行更改,然后进行推送:)
推荐阅读
- java - LONG RAW 列的 jdbc 类型和 java 类型是什么?
- python - 比较列表并根据两者的内容创建新列表
- inkscape - 将文本从 excel 移动到 inkscape
- c# - 在 system32 目录中的现有文件上找不到文件异常
- javascript - Prestashop 在 numbers.json 中更改货币
- sql - 如何在存储库查询中使用任何值
- windows - 运行 venv 的“激活”时出现编码错误
- iis - 访问从单独机器上的主机文件路由的主机名
- kendo-ui - 如何在列模板中使用剑道网格聚合值
- android - Android - 在不拨打网络电话的情况下检查活动的 Internet 连接