How to create a commit and push into repo with GitHub API v3?

前端 未结 6 1661
孤城傲影
孤城傲影 2020-12-02 23:50

I want to create a repository and Commit a few files to it via any Python package. How do I do?

I do not understand how to add files for commit.

6条回答
  •  时光取名叫无心
    2020-12-03 00:23

    Here is a complete snippet:

    def push_to_github(filename, repo, branch, token):
        url="https://api.github.com/repos/"+repo+"/contents/"+filename
    
        base64content=base64.b64encode(open(filename,"rb").read())
    
        data = requests.get(url+'?ref='+branch, headers = {"Authorization": "token "+token}).json()
        sha = data['sha']
    
        if base64content.decode('utf-8')+"\n" != data['content']:
            message = json.dumps({"message":"update",
                                "branch": branch,
                                "content": base64content.decode("utf-8") ,
                                "sha": sha
                                })
    
            resp=requests.put(url, data = message, headers = {"Content-Type": "application/json", "Authorization": "token "+token})
    
            print(resp)
        else:
            print("nothing to update")
    
    token = "lskdlfszezeirzoherkzjehrkzjrzerzer"
    filename="foo.txt"
    repo = "you/test"
    branch="master"
    
    push_to_github(filename, repo, branch, token)
    

提交回复
热议问题