Skip to main content
 首页 » 编程设计

python之如何使用 python 中的 Github api 从字符串计算 SHA

2025年05月04日45jiqing9006

我想使用 Github API 更新文件并将其提交到分支中。我在创建提交时遇到了麻烦。 SHA 与预期的不匹配。

{ 
    'documentation_url': 'https://developer.github.com/enterprise/2.7/v3/repos/contents/', 
    'message': 'pom.xml does not match de42fdd980f9b8067a2af982de46b8d5547e4597' 
} 

我做了以下事情:

import hashlib 
myfile = "new content of my README" 
resulting_file = base64.b64encode(bytes(myfile, "utf-8")) 
file_as_str = str(resulting_file.decode('utf-8')) 
sha = hashlib.sha1(file_as_str.encode('utf-8')).hexdigest() 
 
url = 'https://someurl.com/someproject/contents/README.md?access_token=' + access_token 
data = '{"message": "bla bla", "content": "'+file_as_str+'", "sha": "'+sha+'", "branch": "'+branch+'"}' 
response = requests.put(url, data=data) 

我不想使用库来执行此操作以更好地了解正在发生的事情。可能 SHA 生成不正确,但我无法确定原因。有人可以帮忙吗?

请您参考如下方法:

您不需要为新文件计算 SHA。相反,您必须提供被替换 的文件的 SHA。您可以通过执行 get contents 来获得它使用 requests.get() 在文件上:

url = 'https://api.github.com/repos/someowner/someproject/contents/pom.xml' 
r = requests.get(url) 
sha = r.json()['sha'] 

然后在PUT请求中使用sha的值来更新文件:

with open('myfile', 'rb') as f: 
    content = str(base64.b64encode(f.read()), encoding='utf8') 
    data = {'message': 'bla bla', 'content': content, 'sha': sha, 'branch': branch} 
    r = requests.put(url, json=data)