Created
July 26, 2023 19:45
-
-
Save romanbsd/4856ff5d8fc6c0cd838232296ea6f0cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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