= Overview =

django-view-cache-utils is a django app that provides a method to do advanced view caching. It's basically a patch from converted to stand-alone python package.

= Installation =

$ easy_install django-view-cache-utils or $ pip install django-view-cache-utils or $ hg clone $ cd django-view-cache-utils $ python install

Adding 'view_cache_utils' to INSTALLED_APPS is not necessery, it's a simple python package - just import it when needed.

= Usage =

This package provides cache_page_with_prefix decorator. It tries to get the page from the cache and populate the cache if the page isn't in the cache yet. Works similar to standard Django cache_page decorator, but accept 2 parameters: timeout and callable key_prefix. It makes it easier to fine-tune view caching (implement per-user cache, or cache based on GET parameters, or cache based on user cookies - cache based on anything in request).

Example 1:

# 2 static versions of the my_view response: for authenticated and anonymous users

from view_cache_utils import cache_page_with_prefix

def my_key_prefix(request):
    if request.GET:
        return None #magic value to disable caching

    if request.user.is_authenticated():
        return 'logged_in'
        return 'not_logged_in'

@cache_page_with_prefix(600, my_key_prefix)
def my_view(request):
....... #something is different for authenticated and anonymous users

Example 2:

#cache my_paginated_view based on "page" parameter in query string

def page_key_prefix(request):
    return request.GET.get('page','')

@cache_page_with_prefix(60, page_key_prefix)
def my_paginated_view(request)
.... #page number is passed via 'page' GET parameter and used for pagination

= Notes =

CACHE_MIDDLEWARE_KEY_PREFIX is ignored in cache_page_with_prefix by default. It is consistent with existing behaviour of CacheMiddleware. If you need it you should prepend your keys with CACHE_MIDDLEWARE_KEY_PREFIX manually.

If you define custom key_prefix function and don't want to cache requests with GET parameters (default behaviour for cache_page) you should do it manually as in example 1.

In order to forbid caching key_prefix function should return None value.

If you define key_prefix function that allows several different versions of pages with the same URL you may want to disable client-side cache for that page using @cache_control(must_revalidate=True) decorator as in example.

Please note that kwargs in parameters are not supported, use positional arguments instead (you can't write cache_page_with_prefix(timeout=60, key_prefix=my_func)).