Login

New view decorator to only cache pages for anonymous users

Author:
vaughnkoch
Posted:
October 7, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

This is an addition to Django's cache_page decorator.

I wanted to cache pages for anonymous users but not cache the same page for logged in users. There's middleware to do this at a site-wide level, and it also gives you the ability to partition anonymous users, but then you have to tell Django which pages not to cache with @never_cache.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.utils.decorators import decorator_from_middleware_with_args
from django.middleware.cache import CacheMiddleware


# Note: The standard Django decorator cache_page doesn't give you the anon-nonanon flexibility, 
# and the standard Django 'full-site' cache middleware forces you to cache all pages. 
def cache_page_anonymous(*args, **kwargs):
    """
    Decorator to cache Django views only for anonymous users.
    Use just like the decorator cache_page:

    @cache_page_anonymous(60 * 30)  # cache for 30 mins
    def your_view_here(request):
        ...
    """
    key_prefix = kwargs.pop('key_prefix', None)
    return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], 
                                                                key_prefix=key_prefix, 
                                                                cache_anonymous_only=True)

# Usage:
#
# from your_utils_package_here import cache_page_anonymous
#
# @cache_page_anonymous(30)  # cache for 30 secs
# def my_view(request):
#    ...

More like this

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

Comments

dmalinovsky (on October 10, 2011):

Django also has CACHE_MIDDLEWARE_ANONYMOUS_ONLY setting, which allows to enable per-site cache for anonymous users on page without GET or POST request.

#

Please login first before commenting.