Anybody knows a better way to create a function that would add/commit a database file and push it to Github? The code that I am using has been giving me errors.
TypeError: a bytes-like object is required, not 'str'
Code:
import requests
import base64
import json
import datetime
def push_to_repo_branch(gitHubFileName, fileName, repo_slug, branch, user, token):
message = "Automated update " + str(datetime.datetime.now())
path = "https://api.github.com/repos/%s/branches/%s" % (repo_slug, branch)
r = requests.get(path, auth=(user,token))
if not r.ok:
print("Error when retrieving branch info from %s" % path)
print("Reason: %s [%d]" % (r.text, r.status_code))
rjson = r.json()
treeurl = rjson['commit']['commit']['tree']['url']
# print(treeurl)
r2 = requests.get(treeurl, auth=(user,token))
if not r2.ok:
print("Error when retrieving commit tree from %s" % treeurl)
print("Reason: %s [%d]" % (r2.text, r2.status_code))
r2json = r2.json()
sha = None
for file in r2json['tree']:
# Found file, get the sha code
if file['path'] == gitHubFileName:
sha = file['sha']
# if sha is None after the for loop, we did not find the file name!
if sha is None:
print ("Could not find " + gitHubFileName + " in repos 'tree' ")
with open(fileName) as data:
byte_content = data.read()
content = base64.b64encode(byte_content)
# gathered all the data, now let's push
inputdata = {}
inputdata["path"] = gitHubFileName
inputdata["branch"] = branch
inputdata["message"] = message
inputdata["content"] = content
if sha:
inputdata["sha"] = str(sha)
updateURL = "https://api.github.com/repos/EBISPOT/RDF-platform/contents/" + gitHubFileName
try:
rPut = requests.put(updateURL, auth=(user,token), data = json.dumps(inputdata))
if not rPut.ok:
print("Error when pushing to %s" % updateURL)
print("Reason: %s [%d]" % (rPut.text, rPut.status_code))
except requests.exceptions.RequestException as e:
print('Something went wrong! I will print all the information that is available so you can figure out what happend!')
print(rPut)
print(rPut.headers)
print(rPut.text)
print(e)
with open(fileName) as data:should bewith open(fileName, 'rb') as data:.b64encodeexpects abyteslikeargument. docs.python.org/3/library/base64.html#base64.b64encode andopen()opens a file in'r'(text) mode by default. docs.python.org/3/library/functions.html#open