-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_uploader.py
More file actions
39 lines (33 loc) · 1.4 KB
/
Copy pathgithub_uploader.py
File metadata and controls
39 lines (33 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import requests
import base64
def upload_to_github(github_api_key, repo_owner, repo_name, branch, path, content, commit_message):
headers = {
"Authorization": f"token {github_api_key}",
"Content-Type": "application/json",
}
# Get the file's current state
api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/contents/{path}"
response = requests.get(api_url, headers=headers, params={"ref": branch})
if response.status_code in [200, 404]:
sha = None
if response.status_code == 200:
sha = response.json()["sha"]
# Update or create the file
content_base64 = base64.b64encode(content.encode("utf-8")).decode("utf-8")
data = {
"message": commit_message,
"content": content_base64,
"branch": branch,
}
if sha:
data["sha"] = sha
response = requests.put(api_url, headers=headers, json=data)
if response.status_code in [200, 201]:
print(f"File successfully uploaded to GitHub: {path}")
return True
else:
print(f"File upload to GitHub failed with status code {response.status_code}: {response.text}")
return False
else:
print(f"File retrieval from GitHub failed with status code {response.status_code}: {response.text}")
return False