Skip to content

Instantly share code, notes, and snippets.

@aluminiumgeek
Last active February 16, 2016 18:16
Show Gist options
  • Save aluminiumgeek/99aba8f380edb2b6249d to your computer and use it in GitHub Desktop.
Save aluminiumgeek/99aba8f380edb2b6249d to your computer and use it in GitHub Desktop.
This decorator caches returning value from a function/method
# I suggest you use memcached or redis as backend
import time
import json
from functools import wraps
def cached(timeout=1800):
def wrapper(f):
@wraps(f)
def inner_wrapper(*args, **kwargs):
func_name = '{0}.{1}'.format(f.__module__, f.__name__)
cached_data = CACHE_BACKEND.get(func_name)
if cached_data:
data = json.loads(cached_data)
if data.get('created_at', 0) >= time.time() - timeout and data.get('params') == [list(args), kwargs]:
return data.get('value')
value = f(*args, **kwargs)
cache_data = json.dumps({'created_at': time.time(), 'value': value, 'params': [args, kwargs]})
if len(cache_data) <= SERVER_MAX_VALUE_LENGTH:
CACHE_BACKEND.set(func_name, cache_data)
return value
return inner_wrapper
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment