Skip to content

Instantly share code, notes, and snippets.

@gmemstr
Created January 23, 2017 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmemstr/78d7525b1397c35b7db6cfa858f766c0 to your computer and use it in GitHub Desktop.
Save gmemstr/78d7525b1397c35b7db6cfa858f766c0 to your computer and use it in GitHub Desktop.
Caching to JSON file in Python
# Updated cache script based on mcadmin.
# Includes timelog toggle so dates are not
# logged at all.
import json
import time
def Stash(data, filename, timelog=True):
today = time.strftime("%x")
with open("src/cache/" + filename + ".json") as cache:
_cache = json.load(cache)
if timelog:
_cache[today] = data
else:
_cache = data
with open("src/cache/" + filename + ".json", "w") as cache:
json.dump(_cache, cache, indent=4)
def Fetch(filename, timelog=True, range="today"):
today = time.strftime("%x")
with open("src/cache/" + filename + ".json") as cache:
_data = json.load(cache)
if timelog:
if range == "today":
return _data[today]
if range == "all":
return _data
else:
return _data[range]
else:
return _data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment