python 3.7 compatibility and secret handling

Payload is no longer appended using a python 3.9 feature.
The last refresh time is no longer stored as it was not used.
This commit is contained in:
Suksi
2021-08-31 01:26:24 +03:00
parent 52aec70a6e
commit 605b594863
+7 -14
View File
@@ -1,5 +1,10 @@
import json, time, requests, re, os
secrets = {
"user_id": os.getenv("USER_ID"),
"access_token": os.getenv("ACCESS_TOKEN")
}
def read_data_from_file(filename):
with open(filename, "r") as file:
return json.loads(file.read())
@@ -8,21 +13,12 @@ def write_data_to_file(filename, data):
with open(filename, "w") as file:
file.write(json.dumps(data, indent=4))
secrets = {
"user_id": os.getenv("USER_ID"),
"access_token": os.getenv("ACCESS_TOKEN")
}
if "last_refresh" in os.environ:
secrets["last_refresh"] = os.gerenv("LAST_REFRESH")
else:
secrets["last_refresh"] = 0
def call(url, payload):
""" Calls the instagram Basic Display API with the given url and payload.
Returns the response body as a dict.
Raises HTTPError if the HTTP response code is 4XX or 5XX. """
# append access token to payload
payload |= {"access_token": secrets["access_token"]}
payload["access_token"] = secrets["access_token"]
response = requests.get("https://graph.instagram.com" + url, params=payload, timeout=1)
response.raise_for_status()
return response.json()
@@ -34,9 +30,7 @@ def refresh_instagram_access_token():
response_body = call("/refresh_access_token", {"grant_type": "ig_refresh_token"})
expiration_date = time.time() + response_body["expires_in"]
expiration_date = time.strftime("%Y.%m.%d %H:%M", time.gmtime(expiration_date))
secrets["last_refresh"] = time.time()
print(f"Instagram access token refreshed. Expires on {expiration_date}")
return secrets
def format_media(media):
""" Writes the media returned by the IG API in the desired format. """
@@ -60,7 +54,6 @@ def fetch_instagram_media():
return format_media(response_body["data"])
if __name__ == "__main__":
secrets = refresh_instagram_access_token()
os.environ["LAST_REFRESH"] = str(secrets["last_refresh"])
refresh_instagram_access_token()
media = fetch_instagram_media()
write_data_to_file("instagram_media.json", media)