Login

New view decorator to only cache pages for anonymous users

Author:
vaughnkoch
Posted:
October 7, 2010
Language:
Python
Version:
1.2
Tags:
cache view decorator anonymous
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. anonymous_required decorator by yetty 1 year, 12 months ago
  2. Cache view by user (and anonymous) by rafaelsdm 3 years, 10 months ago
  3. Anonymous required decorator by Motanelu 5 years, 5 months ago
  4. create and authenticate an anonymous user by chr15m 5 years, 9 months ago
  5. group_required decorator by msanders 5 years, 10 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.