Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created July 26, 2023 19:45
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 romanbsd/4856ff5d8fc6c0cd838232296ea6f0cf to your computer and use it in GitHub Desktop.
Save romanbsd/4856ff5d8fc6c0cd838232296ea6f0cf to your computer and use it in GitHub Desktop.
def cache_disk(seconds = 900, cache_folder="/tmp"):
def doCache(f):
def inner_function(*args, **kwargs):
# calculate a cache key based on the decorated method signature
key = sha1(str(f.__module__) + str(f.__name__) + str(args) + str(kwargs)).hexdigest()
filepath = os.path.join(cache_folder, key)
# verify that the cached object exists and is less than $seconds old
if os.path.exists(filepath):
modified = os.path.getmtime(filepath)
age_seconds = time.time() - modified
if age_seconds < seconds:
return pickle.load(open(filepath, "rb"))
# call the decorated function...
result = f(*args, **kwargs)
# ... and save the cached object for next time
pickle.dump(result, open(filepath, "wb"))
return result
return inner_function
return doCache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment