from django.conf import settings from django.db.models.query import QuerySet from django.utils.cache import cache from django.utils.hashcompat import md5_constructor def stringify_object(obj): if isinstance(obj, QuerySet): return obj.query.as_sql() return unicode(obj) def key_from_args(*args, **kwargs): strings = [] for arg in args: strings.append(stringify_object(arg)) for k,v in kwargs.items(): strings.append('%s=%s' % (k, stringify_object(v))) return md5_constructor(''.join(strings).hexdigest()) def cached_filter(func, timeout=300): def inner(*args, **kwargs): if settings.DEBUG: return func(*args, **kwargs) cache_key = key_from_args(*args, **kwargs) result = cache.get(cache_key) if not result: result = func(*args, **kwargs) cache.set(cache_key, result, timeout) return result inner._decorated_function = func return inner