I need a per user caching. The regular view caching does unfortunately not support user-based caching.
I tried the template fragment caching like this:
The following is an improved version for the accepted solution does not consider the request parameters.
decorator_of_cache_per_user.py
from django.core.cache import cache as core_cache
def cache_key(request):
if request.user.is_anonymous():
user = 'anonymous'
else:
user = request.user.id
q = getattr(request, request.method)
q.lists()
urlencode = q.urlencode(safe='()')
CACHE_KEY = 'view_cache_%s_%s_%s' % (request.path, user, urlencode)
return CACHE_KEY
def cache_per_user_function(ttl=None, prefix=None, cache_post=False):
def decorator(function):
def apply_cache(request, *args, **kwargs):
CACHE_KEY = cache_key(request)
if prefix:
CACHE_KEY = '%s_%s' % (prefix, CACHE_KEY)
if not cache_post and request.method == 'POST':
can_cache = False
else:
can_cache = True
if can_cache:
response = core_cache.get(CACHE_KEY, None)
else:
response = None
if not response:
response = function(request, *args, **kwargs)
if can_cache:
core_cache.set(CACHE_KEY, response, ttl)
return response
return apply_cache
return decorator