Python/decorators
Appearance
< Python
caching HTTP requests
def persist_to_file(func):
def decorator(url, cache=True):
filename = url
filename = filename.replace(BASE_URL + "/","")
filename = filename.replace("/","_")
filename = filename.replace("?","-")
filename = CACHE_FOLDER + filename + ".pickle"
if cache == False:
return func(url)
if os.path.isfile(filename):
with open (filename, 'rb') as cf:
content = pickle.load(cf)
return content
else:
content = func(url)
with open(filename, 'wb') as cf:
pickle.dump(content, cf)
return content
return decorator
@persist_to_file
def request_json_api(url):
"""Access API, using username and password. Return JSON"""
response = requests.get(url, auth=(USER, PASS))
json_data = response.json()
return json_data