Skip to content

Instantly share code, notes, and snippets.

@devadutta
Created May 6, 2023 22:41
Show Gist options
  • Save devadutta/561a4ed3d75ce2def1d828657992b11d to your computer and use it in GitHub Desktop.
Save devadutta/561a4ed3d75ce2def1d828657992b11d to your computer and use it in GitHub Desktop.
import base64
import hashlib
import json
import os
import requests
# Replace these variables with your information
GITHUB_ACCESS_TOKEN = "your_access_token"
REPO_OWNER = "your_github_username"
REPO_NAME = "your_repo_name"
DB_FILE_PATH = "path/to/your/sqlite.db"
# GitHub API base URL
BASE_URL = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}"
# Set the required headers for API requests
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"token {GITHUB_ACCESS_TOKEN}"
}
def get_file_sha_and_content():
response = requests.get(f"{BASE_URL}/contents/{os.path.basename(DB_FILE_PATH)}", headers=headers)
if response.status_code == 200:
content = json.loads(response.text)
return content["sha"], content["content"]
else:
print(f"Error: {response.status_code}")
return None, None
def commit_and_push_file(file_sha, new_content):
commit_msg = "Update SQLite DB backup"
data = {
"message": commit_msg,
"content": new_content,
"sha": file_sha
}
response = requests.put(f"{BASE_URL}/contents/{os.path.basename(DB_FILE_PATH)}", data=json.dumps(data), headers=headers)
if response.status_code == 200:
print(f"File committed and pushed with message: '{commit_msg}'")
else:
print(f"Error: {response.status_code}")
def main():
sha, old_content = get_file_sha_and_content()
if sha is not None and old_content is not None:
with open(DB_FILE_PATH, "rb") as db_file:
new_content = base64.b64encode(db_file.read()).decode("utf-8")
# Check if file contents have changed
old_md5 = hashlib.md5(base64.b64decode(old_content)).hexdigest()
new_md5 = hashlib.md5(base64.b64decode(new_content)).hexdigest()
if old_md5 != new_md5:
commit_and_push_file(sha, new_content)
else:
print("No changes in the SQLite DB file since the last commit.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment