首页 > 解决方案 > 创建/更新 .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() 导入的字符串。

标签: pythonjsonpython-3.xgitgithub

解决方案


虽然我没有找到任何方法可以在不克隆本地目录中的 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 或您想要的任何其他文件进行更改,然后进行推送:)


推荐阅读