in this version i include in the cache key the different *args and **kwargs based on the accepted answer
def cache_per_user(ttl=None, prefix=None, cache_post=False):
'''Decorator that caches the view for each user
* ttl - Cache lifetime, not sending this parameter means the
cache will last until the server restarts or decides to remove it
* prefix - Prefix to be used to cache the response. if not
be informed will use 'view_cache_'+function.__name__
* cache_post - Informs whether to cache POST requests
* Cache for anonymous users is shared with everyone
* The cache key will be one of the possible options:
'%s_%s'%(prefix, user.id)
'%s_anonymous'%(prefix)
'view_cache_%s_%s'%(function.__name__, user.id)
'view_cache_%s_anonymous'%(function.__name__)
'''
def decorator(function):
def apply_cache(request, *args, **kwargs):
if request.user.is_anonymous():
user = 'anonymous'
else:
user = request.user.id
if prefix:
base_key = '%s_%s' % (prefix, user)
else:
base_key = 'view_cache_%s_%s' % (function.__name__, user)
# Include function arguments in the cache key
args_key = '_'.join([str(arg) for arg in args])
# Include keyword arguments in the cache key
kwargs_key = '_'.join(['%s=%s' % (key, value) for key, value in kwargs.items()])
# Generate the cache key
CACHE_KEY = '%s_%s_%s' % (base_key, args_key, kwargs_key)
if not cache_post and request.method == 'POST':
can_cache = False
else:
can_cache = True
if can_cache:
response = cache.get(CACHE_KEY, None)
else:
response = None
if not response:
response = function(request, *args, **kwargs)
if can_cache:
cache.set(CACHE_KEY, response, ttl)
return response
return apply_cache
return decorator