How to calculate SHA from a string with the Github api in python?
<p>I want to update a file with the Github API and commit it into a branch. I have troubles creating the commit. The SHA does not match the expected one.</p>

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

<p>I do the following:</p>

<pre><code>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)
</code></pre>

<p>I would not like to use a lib to do this to better understand what is happening. probably the SHA is not generated properly, but I cannot identify why. Could someone help?</p>

<p>GitHub calculates hashes as followes:</p>

<pre><code>sha1("blob " + filesize + "\0" + data)
</code></pre>

<p>so use this code:</p>

<pre><code>with open(filepath, 'rb') as file_for_hash:
    data = file_for_hash.read()
    filesize = len(data)
sha = hashlib.sha1("blob " + filesize + "\0" + data).hexdigest()
</code></pre>

python git github-api