【问题标题】:Create/Update .json file to GitHub Private Repository without making local working directory or cloning repo using Python创建/更新 .json 文件到 GitHub Private Repository,无需使用 Python 创建本地工作目录或克隆 repo
【发布时间】:2021-06-23 01:42:40
【问题描述】:

我有一个 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() 导入的字符串..

【问题讨论】:

    标签: python json python-3.x git github


    【解决方案1】:

    虽然我没有找到任何方法可以在不克隆本地目录中的 repo 的情况下做到这一点

    但是,如果您想在使用本地目录时这样做:

    将私有仓库克隆到本地目录的功能。您还需要创建个人访问令牌 (you can create here) 并确保授予 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")
    

    拉取repo的函数:

    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 或您想要的任何其他文件进行更改,然后进行推送 :)

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2015-01-09
      • 2017-03-11
      • 2012-10-21
      • 1970-01-01
      • 2020-06-28
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多