paper_hashtag_federation/instance_scanner/picklecache.py
Trolli Schmittlauch 2c22aaede5 import finished university paper & pseudonymise
- dropping all history from the university paper in case it contains
sensitive data
2019-08-05 23:59:43 +02:00

27 lines
1 KiB
Python

from functools import wraps
import pickle
import os
def cache_return(func):
"""caches the return value of a function locally as a pickle file"""
@wraps(func)
def wrapped(*args, **kwargs):
CACHEDIR = "__picklecache__"
if not os.path.exists(CACHEDIR):
os.mkdir(CACHEDIR)
cachefilename = "{}{}{}.pickle".format(func.__name__, args, kwargs)
# if cached serialization exists, comparereturn it
if os.path.exists(os.path.join(CACHEDIR, cachefilename)):
with open(os.path.join(CACHEDIR, cachefilename), "rb") as loadfile:
t = pickle.load(loadfile)
if args == t[0] and kwargs == t[1]:
return t[2]
# otherwise call function and serialize its return value
with open(os.path.join(CACHEDIR, cachefilename), "wb") as dumpfile:
funcreturn = func(*args, **kwargs)
t = (args, kwargs, funcreturn)
pickle.dump(t, dumpfile)
return funcreturn
return wrapped