from functools import wraps
def memoize(obj):
'''Memoization decorator for callables'''
memo = obj.memo = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in memo:
memo[key] = obj(*args, **kwargs)
return memo[key]
return memoizer
def memoize(timeout=60):
'''
Memoization with django's cache backend
Refer:
- https://djangosnippets.org/snippets/564/
- http://pythonhosted.org/django-memoize/
'''
from hashlib import sha1
from django.core.cache import cache
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def _func(*args, **kwargs):
key_seed = ':'.join([
'memoize',
str(func.__module__),
str(func.__name__),
str(args),
str(kwargs),
])
key = sha1(key_seed).hexdigest()
result = cache.get(key)
if result is None:
result = func(*args, **kwargs)
cache.set(key, result, timeout)
return result
return _func
return decorator
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from functools import wraps
from lib.cache import cache as default_cache
from flask import request
def cache_by_args(timeout=5 * 60, prefix='', cache=None):
"""
Use cases:
@cache_by_args(3600)
def f(x, y):
pass
from some.package import func
res = cache_by_args(3600)(func)(x, y)
"""
cache = cache or default_cache
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
force_update = kwargs.pop('_force_update', False)
cache_key = '{0}{1}.{2}:{3}'.format(
prefix, f.__module__, f.__name__, ','.join(
six.text_type(a)
for a in list(args) +
['{}={}'.format(k, v) for k, v in kwargs.items()]))
if not (force_update or request.cache_control.no_cache):
rv = cache.get(cache_key)
if rv is not None:
return rv
rv = f(*args, **kwargs)
cache.set(cache_key, rv, timeout=timeout)
return rv
return decorated_function
return decorator