Login

Conditional cache decorator

Author:
alexisbellido
Posted:
August 23, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

A decorator to bypass per-site cache if the user is authenticated. Based on django.views.decorators.cache.never_cache.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
"""
A decorator to bypass per-site cache if the user is authenticated. Based on django.views.decorators.cache.never_cache.
See: http://stackoverflow.com/questions/12060036/why-django-1-4-per-site-cache-does-not-work-correctly-with-cache-middleware-anon
"""     
        
from django.utils.decorators import available_attrs
from django.utils.cache import add_never_cache_headers
from functools import wraps

def conditional_cache(view_func):
    """
    Checks the user and if it's authenticated pass it through never_cache.
    This version uses functools.wraps for the wrapper function.
    """ 
    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        if request.user.is_authenticated():
            add_never_cache_headers(response)
        return response
    return _wrapped_view_func

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

chrisdpratt (on August 23, 2012):

How about just using CACHE_MIDDLEWARE_ANONYMOUS_ONLY?

#

Please login first before commenting.