Skip to content

Instantly share code, notes, and snippets.

@OhadRubin
Created September 23, 2023 12:18
Show Gist options
  • Save OhadRubin/122be389b9481a78ffce4fd7514a9f87 to your computer and use it in GitHub Desktop.
Save OhadRubin/122be389b9481a78ffce4fd7514a9f87 to your computer and use it in GitHub Desktop.
import requests
import json
class GistDictionary:
def __init__(self, github_token, base_gist_id):
self.github_token = github_token
self.base_gist_id = base_gist_id
self.headers = {
"Authorization": f"token {github_token}",
"Accept": "application/vnd.github.v3+json",
}
self.base_api_url = "https://api.github.com/gists/"
# Fetch the base gist on initialization
self.store = self.fetch_base_gist()
def fetch_base_gist(self):
response = requests.get(self.base_api_url + self.base_gist_id, headers=self.headers)
response.raise_for_status()
content = response.json()['files']['page_table']['content']
return json.loads(content)
def update_base_gist(self):
data = {
'files': {
'page_table': {
'content': json.dumps(self.store)
}
}
}
response = requests.patch(self.base_api_url + self.base_gist_id, headers=self.headers, json=data)
response.raise_for_status()
def __setitem__(self, key, value):
data = {
"files": {key: {"content": value}},
"public": False
}
response = requests.post(self.base_api_url, headers=self.headers, json=data)
response.raise_for_status()
# update the store and base gist
self.store[key] = response.json()["id"]
self.update_base_gist()
def __getitem__(self, key):
gist_id = self.store[key]
url = self.base_api_url + gist_id
response = requests.get(url, headers=self.headers)
response.raise_for_status()
return response.json()["files"][key]["content"]
# Example usage:
gist_dict = GistDictionary('your_github_token', 'base_gist_id')
gist_dict['key1'] = 'value1' # set a key value pair
print(gist_dict['key1']) # get value for a key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment