This alone can cache the return value in memcached
@cached(time=1200)
def functionToCache(arguments):
return arguments
Especially, I find it convenient when doing scraping and development involving external data.
pip install python-memcached
memcached-decorater.py
def decorator_with_args(decorator_to_enhance):
"""
A function that gives an argument to the decorator and returns it
"""
def decorator_maker(*args, **kwargs) :
def decorator_wrapper(func) :
return decorator_to_enhance(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
@decorator_with_args
def cached(func, *args, **kwargs):
"""
Decorator that caches results using function names and arguments as keys
How to use
@cached(time=1200)
def functionToCache(arguments):
"""
def wrapper(*pars):
key = func.__name__ + '_' + '_'.join([str(par) for par in pars])
print key
client = memcache.Client(['127.0.0.1:11211'])
val = client.get(key)
if not val:
val = func(*pars)
try:
client.set(key, val, time=kwargs['time'])
except:
pass #Please
return val
return wrapper
gae-memcache-decorator.py https://gist.github.com/abahgat/1395810
Recommended Posts