django.views.decorators.cache.cache_page()
A more granular way to use the caching framework is by caching the output of individual views. django.views.decorators.cache
defines a cache_page
decorator that will automatically cache the view’s response for you. It’s easy to use:
from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ...
cache_page
takes a single argument: the cache timeout, in seconds. In the above 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 = [ url(r'^foo/([0-9]{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.
cache_page
can also take an optional keyword argument, cache
, which directs the decorator to use a specific cache (from your CACHES
setting) when caching view results. By default, the default
cache will be used, but you can specify any cache you want:
@cache_page(60 * 15, cache="special_cache") def my_view(request): ...
You can also override the cache prefix on a per-view basis. cache_page
takes an optional keyword argument, key_prefix
, which works in the same way as the CACHE_MIDDLEWARE_KEY_PREFIX
setting for the middleware. It can be used like this:
@cache_page(60 * 15, key_prefix="site1") def my_view(request): ...
The key_prefix
and cache
arguments may be specified together. The key_prefix
argument and the KEY_PREFIX
specified under CACHES
will be concatenated.
Please login to continue.