Thursday, June 16, 2011

Per View Caching in Django

A more granular way to use the caching framework is by caching the output of individual views. This has the same effects as the per-site cache (including the omission of caching on requests with GET and POST parameters). It applies to whichever views you specify, rather than the whole site.

Do this by using a decorator, which is a wrapper around your view function that alters its behavior to use caching. The per-view cache decorator is called cache_page and is located in the django.views.decorators.cache module, for example:

from django.views.decorators.cache import cache_page

def my_view(request, param):
# ...
my_view = cache_page(my_view, 60 * 15)

Alternatively, you can use decorator syntax. This example is equivalent to the preceding one:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request, param):
# ...

cache_page takes a single argument: the cache timeout, in seconds. In the preceding example, the result of the my_view() view will be cached for 15 minutes. (Note that we’ve written it as 60 * 15 for the purpose of readability. 60 * 15 will be evaluated to 900—that is, 15 minutes multiplied by 60 seconds per minute.)
The per-view cache, like the per-site cache, is keyed off of the URL. If multiple URLs point at the same view, each URL will be cached separately. Continuing the my_view example, if your URLconf looks like this:

urlpatterns = ('',
(r'^foo/(\d{1,2})/$', my_view),

then requests to /foo/1/ and /foo/23/ will be cached separately, as you may expect. But once a particular URL (e.g., /foo/23/) has been requested, subsequent requests to that URL will use the cache.
Read more here

No comments:

Post a Comment