New view decorator to only cache pages for anonymous users

 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. Get the Django decorator/middleware cache key for given URL by s29 1 year, 6 months ago
  2. Per-site vary cache on language by fneumann 5 years, 7 months ago
  3. Conditional cache decorator by alexisbellido 8 months, 4 weeks ago
  4. HTTP Authorization Middleware/Decorator by schinckel 3 years, 8 months ago
  5. cache_page that does nothing by peterbe 3 years, 9 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.

#

(Forgotten your password?)