2008-08-24 06:25:40 +08:00
|
|
|
.. _topics-cache:
|
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
========================
|
|
|
|
Django's cache framework
|
|
|
|
========================
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
A fundamental trade-off in dynamic Web sites is, well, they're dynamic. Each
|
2006-05-02 09:31:56 +08:00
|
|
|
time a user requests a page, the Web server makes all sorts of calculations --
|
|
|
|
from database queries to template rendering to business logic -- to create the
|
|
|
|
page that your site's visitor sees. This is a lot more expensive, from a
|
2008-07-26 02:51:32 +08:00
|
|
|
processing-overhead perspective, than your standard
|
|
|
|
read-a-file-off-the-filesystem server arrangement.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
For most Web applications, this overhead isn't a big deal. Most Web
|
|
|
|
applications aren't washingtonpost.com or slashdot.org; they're simply small-
|
|
|
|
to medium-sized sites with so-so traffic. But for medium- to high-traffic
|
|
|
|
sites, it's essential to cut as much overhead as possible.
|
|
|
|
|
|
|
|
That's where caching comes in.
|
|
|
|
|
|
|
|
To cache something is to save the result of an expensive calculation so that
|
|
|
|
you don't have to perform the calculation next time. Here's some pseudocode
|
2006-05-02 09:59:39 +08:00
|
|
|
explaining how this would work for a dynamically generated Web page::
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
given a URL, try finding that page in the cache
|
|
|
|
if the page is in the cache:
|
|
|
|
return the cached page
|
|
|
|
else:
|
|
|
|
generate the page
|
|
|
|
save the generated page in the cache (for next time)
|
|
|
|
return the generated page
|
|
|
|
|
|
|
|
Django comes with a robust cache system that lets you save dynamic pages so
|
|
|
|
they don't have to be calculated for each request. For convenience, Django
|
|
|
|
offers different levels of cache granularity: You can cache the output of
|
|
|
|
specific views, you can cache only the pieces that are difficult to produce, or
|
|
|
|
you can cache your entire site.
|
|
|
|
|
|
|
|
Django also works well with "upstream" caches, such as Squid
|
|
|
|
(http://www.squid-cache.org/) and browser-based caches. These are the types of
|
|
|
|
caches that you don't directly control but to which you can provide hints (via
|
|
|
|
HTTP headers) about which parts of your site should be cached, and how.
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
Setting up the cache
|
|
|
|
====================
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The cache system requires a small amount of setup. Namely, you have to tell it
|
|
|
|
where your cached data should live -- whether in a database, on the filesystem
|
|
|
|
or directly in memory. This is an important decision that affects your cache's
|
|
|
|
performance; yes, some cache types are faster than others.
|
|
|
|
|
|
|
|
Your cache preference goes in the ``CACHE_BACKEND`` setting in your settings
|
|
|
|
file. Here's an explanation of all available values for CACHE_BACKEND.
|
|
|
|
|
|
|
|
Memcached
|
|
|
|
---------
|
|
|
|
|
|
|
|
By far the fastest, most efficient type of cache available to Django, Memcached
|
|
|
|
is an entirely memory-based cache framework originally developed to handle high
|
|
|
|
loads at LiveJournal.com and subsequently open-sourced by Danga Interactive.
|
|
|
|
It's used by sites such as Slashdot and Wikipedia to reduce database access and
|
|
|
|
dramatically increase site performance.
|
|
|
|
|
|
|
|
Memcached is available for free at http://danga.com/memcached/ . It runs as a
|
|
|
|
daemon and is allotted a specified amount of RAM. All it does is provide an
|
2009-03-02 13:46:04 +08:00
|
|
|
interface -- a *lightning-fast* interface -- for adding, retrieving and
|
2006-05-02 09:31:56 +08:00
|
|
|
deleting arbitrary data in the cache. All data is stored directly in memory,
|
|
|
|
so there's no overhead of database or filesystem usage.
|
|
|
|
|
|
|
|
After installing Memcached itself, you'll need to install the Memcached Python
|
2007-03-26 07:29:31 +08:00
|
|
|
bindings. Two versions of this are available. Choose and install *one* of the
|
|
|
|
following modules:
|
|
|
|
|
|
|
|
* The fastest available option is a module called ``cmemcache``, available
|
2008-11-14 16:02:46 +08:00
|
|
|
at http://gijsbert.org/cmemcache/ .
|
2007-03-26 07:29:31 +08:00
|
|
|
|
|
|
|
* If you can't install ``cmemcache``, you can install ``python-memcached``,
|
|
|
|
available at ftp://ftp.tummy.com/pub/python-memcached/ . If that URL is
|
|
|
|
no longer valid, just go to the Memcached Web site
|
|
|
|
(http://www.danga.com/memcached/) and get the Python bindings from the
|
|
|
|
"Client APIs" section.
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2008-11-14 16:02:46 +08:00
|
|
|
.. versionadded:: 1.0
|
|
|
|
The ``cmemcache`` option is new in 1.0. Previously, only
|
|
|
|
``python-memcached`` was supported.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
To use Memcached with Django, set ``CACHE_BACKEND`` to
|
|
|
|
``memcached://ip:port/``, where ``ip`` is the IP address of the Memcached
|
|
|
|
daemon and ``port`` is the port on which Memcached is running.
|
|
|
|
|
|
|
|
In this example, Memcached is running on localhost (127.0.0.1) port 11211::
|
|
|
|
|
|
|
|
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
|
|
|
|
|
|
|
|
One excellent feature of Memcached is its ability to share cache over multiple
|
|
|
|
servers. To take advantage of this feature, include all server addresses in
|
|
|
|
``CACHE_BACKEND``, separated by semicolons. In this example, the cache is
|
|
|
|
shared over Memcached instances running on IP address 172.19.26.240 and
|
|
|
|
172.19.26.242, both on port 11211::
|
|
|
|
|
|
|
|
CACHE_BACKEND = 'memcached://172.19.26.240:11211;172.19.26.242:11211/'
|
|
|
|
|
|
|
|
Memory-based caching has one disadvantage: Because the cached data is stored in
|
|
|
|
memory, the data will be lost if your server crashes. Clearly, memory isn't
|
|
|
|
intended for permanent data storage, so don't rely on memory-based caching as
|
|
|
|
your only data storage. Actually, none of the Django caching backends should be
|
|
|
|
used for permanent storage -- they're all intended to be solutions for caching,
|
|
|
|
not storage -- but we point this out here because memory-based caching is
|
|
|
|
particularly temporary.
|
|
|
|
|
|
|
|
Database caching
|
|
|
|
----------------
|
|
|
|
|
|
|
|
To use a database table as your cache backend, first create a cache table in
|
|
|
|
your database by running this command::
|
|
|
|
|
|
|
|
python manage.py createcachetable [cache_table_name]
|
|
|
|
|
|
|
|
...where ``[cache_table_name]`` is the name of the database table to create.
|
|
|
|
(This name can be whatever you want, as long as it's a valid table name that's
|
|
|
|
not already being used in your database.) This command creates a single table
|
|
|
|
in your database that is in the proper format that Django's database-cache
|
|
|
|
system expects.
|
|
|
|
|
|
|
|
Once you've created that database table, set your ``CACHE_BACKEND`` setting to
|
2007-10-22 03:10:10 +08:00
|
|
|
``"db://tablename"``, where ``tablename`` is the name of the database table.
|
|
|
|
In this example, the cache table's name is ``my_cache_table``::
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
CACHE_BACKEND = 'db://my_cache_table'
|
|
|
|
|
|
|
|
Database caching works best if you've got a fast, well-indexed database server.
|
|
|
|
|
|
|
|
Filesystem caching
|
|
|
|
------------------
|
|
|
|
|
|
|
|
To store cached items on a filesystem, use the ``"file://"`` cache type for
|
|
|
|
``CACHE_BACKEND``. For example, to store cached data in ``/var/tmp/django_cache``,
|
|
|
|
use this setting::
|
|
|
|
|
|
|
|
CACHE_BACKEND = 'file:///var/tmp/django_cache'
|
|
|
|
|
|
|
|
Note that there are three forward slashes toward the beginning of that example.
|
|
|
|
The first two are for ``file://``, and the third is the first character of the
|
|
|
|
directory path, ``/var/tmp/django_cache``.
|
|
|
|
|
|
|
|
The directory path should be absolute -- that is, it should start at the root
|
|
|
|
of your filesystem. It doesn't matter whether you put a slash at the end of the
|
|
|
|
setting.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Make sure the directory pointed-to by this setting exists and is readable and
|
|
|
|
writable by the system user under which your Web server runs. Continuing the
|
|
|
|
above example, if your server runs as the user ``apache``, make sure the
|
|
|
|
directory ``/var/tmp/django_cache`` exists and is readable and writable by the
|
|
|
|
user ``apache``.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Local-memory caching
|
|
|
|
--------------------
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
If you want the speed advantages of in-memory caching but don't have the
|
|
|
|
capability of running Memcached, consider the local-memory cache backend. This
|
|
|
|
cache is multi-process and thread-safe. To use it, set ``CACHE_BACKEND`` to
|
|
|
|
``"locmem:///"``. For example::
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
CACHE_BACKEND = 'locmem:///'
|
2009-03-11 21:27:03 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Note that each process will have its own private cache instance, which means no
|
|
|
|
cross-process caching is possible. This obviously also means the local memory
|
|
|
|
cache isn't particularly memory-efficient, so it's probably not a good choice
|
|
|
|
for production environments.
|
2006-02-24 14:09:35 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Dummy caching (for development)
|
|
|
|
-------------------------------
|
2006-01-04 07:41:31 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
|
|
|
|
just implements the cache interface without doing anything.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
This is useful if you have a production site that uses heavy-duty caching in
|
|
|
|
various places but a development/test environment on which you don't want to
|
2007-09-05 06:44:35 +08:00
|
|
|
cache. As a result, your development environment won't use caching and your
|
|
|
|
production environment still will. To activate dummy caching, set
|
|
|
|
``CACHE_BACKEND`` like so::
|
|
|
|
|
|
|
|
CACHE_BACKEND = 'dummy:///'
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2008-07-26 02:51:32 +08:00
|
|
|
Using a custom cache backend
|
|
|
|
----------------------------
|
|
|
|
|
2008-09-02 11:40:42 +08:00
|
|
|
.. versionadded:: 1.0
|
2008-07-26 02:51:32 +08:00
|
|
|
|
|
|
|
While Django includes support for a number of cache backends out-of-the-box,
|
2008-09-08 06:55:31 +08:00
|
|
|
sometimes you might want to use a customized cache backend. To use an external
|
|
|
|
cache backend with Django, use a Python import path as the scheme portion (the
|
|
|
|
part before the initial colon) of the ``CACHE_BACKEND`` URI, like so::
|
2008-07-26 02:51:32 +08:00
|
|
|
|
|
|
|
CACHE_BACKEND = 'path.to.backend://'
|
|
|
|
|
|
|
|
If you're building your own backend, you can use the standard cache backends
|
|
|
|
as reference implementations. You'll find the code in the
|
|
|
|
``django/core/cache/backends/`` directory of the Django source.
|
|
|
|
|
2008-09-08 06:55:31 +08:00
|
|
|
Note: Without a really compelling reason, such as a host that doesn't support
|
2008-09-10 03:53:57 +08:00
|
|
|
them, you should stick to the cache backends included with Django. They've
|
2008-09-08 06:55:31 +08:00
|
|
|
been well-tested and are easy to use.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
CACHE_BACKEND arguments
|
|
|
|
-----------------------
|
|
|
|
|
|
|
|
All caches may take arguments. They're given in query-string style on the
|
|
|
|
``CACHE_BACKEND`` setting. Valid arguments are:
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2005-07-20 04:49:07 +08:00
|
|
|
timeout
|
|
|
|
Default timeout, in seconds, to use for the cache. Defaults to 5
|
|
|
|
minutes (300 seconds).
|
|
|
|
|
|
|
|
max_entries
|
2008-12-03 13:49:37 +08:00
|
|
|
For the ``locmem``, ``filesystem`` and ``database`` backends, the
|
|
|
|
maximum number of entries allowed in the cache before it is cleaned.
|
|
|
|
Defaults to 300.
|
2005-07-20 04:49:07 +08:00
|
|
|
|
|
|
|
cull_percentage
|
|
|
|
The percentage of entries that are culled when max_entries is reached.
|
2005-07-16 01:05:43 +08:00
|
|
|
The actual percentage is 1/cull_percentage, so set cull_percentage=3 to
|
|
|
|
cull 1/3 of the entries when max_entries is reached.
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
A value of 0 for cull_percentage means that the entire cache will be
|
2005-07-20 04:49:07 +08:00
|
|
|
dumped when max_entries is reached. This makes culling *much* faster
|
2005-07-16 01:05:43 +08:00
|
|
|
at the expense of more cache misses.
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
In this example, ``timeout`` is set to ``60``::
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2005-09-11 23:12:30 +08:00
|
|
|
CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=60"
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
In this example, ``timeout`` is ``30`` and ``max_entries`` is ``400``::
|
|
|
|
|
2008-12-03 13:49:37 +08:00
|
|
|
CACHE_BACKEND = "locmem:///?timeout=30&max_entries=400"
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2005-07-20 04:49:07 +08:00
|
|
|
Invalid arguments are silently ignored, as are invalid values of known
|
2005-07-16 01:05:43 +08:00
|
|
|
arguments.
|
|
|
|
|
2005-07-20 04:49:07 +08:00
|
|
|
The per-site cache
|
2005-07-16 01:05:43 +08:00
|
|
|
==================
|
|
|
|
|
2008-09-02 11:40:42 +08:00
|
|
|
.. versionchanged:: 1.0
|
|
|
|
(previous versions of Django only provided a single ``CacheMiddleware`` instead
|
|
|
|
of the two pieces described below).
|
2008-08-09 23:07:45 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Once the cache is set up, the simplest way to use caching is to cache your
|
2008-08-09 23:07:45 +08:00
|
|
|
entire site. You'll need to add
|
|
|
|
``'django.middleware.cache.UpdateCacheMiddleware'`` and
|
2008-08-15 22:17:24 +08:00
|
|
|
``'django.middleware.cache.FetchFromCacheMiddleware'`` to your
|
2005-10-09 08:55:08 +08:00
|
|
|
``MIDDLEWARE_CLASSES`` setting, as in this example::
|
2005-07-20 04:49:07 +08:00
|
|
|
|
|
|
|
MIDDLEWARE_CLASSES = (
|
2008-08-09 23:07:45 +08:00
|
|
|
'django.middleware.cache.UpdateCacheMiddleware',
|
2006-05-26 12:05:02 +08:00
|
|
|
'django.middleware.common.CommonMiddleware',
|
2008-08-09 23:07:45 +08:00
|
|
|
'django.middleware.cache.FetchFromCacheMiddleware',
|
2005-07-20 04:49:07 +08:00
|
|
|
)
|
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
No, that's not a typo: the "update" middleware must be first in the list,
|
|
|
|
and the "fetch" middleware must be last. The details are a bit obscure, but
|
|
|
|
see `Order of MIDDLEWARE_CLASSES`_ below if you'd like the full story.
|
2005-09-03 05:22:49 +08:00
|
|
|
|
2005-11-20 13:17:55 +08:00
|
|
|
Then, add the following required settings to your Django settings file:
|
2005-07-20 04:49:07 +08:00
|
|
|
|
|
|
|
* ``CACHE_MIDDLEWARE_SECONDS`` -- The number of seconds each page should be
|
|
|
|
cached.
|
|
|
|
* ``CACHE_MIDDLEWARE_KEY_PREFIX`` -- If the cache is shared across multiple
|
|
|
|
sites using the same Django installation, set this to the name of the site,
|
|
|
|
or some other string that is unique to this Django instance, to prevent key
|
|
|
|
collisions. Use an empty string if you don't care.
|
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
The cache middleware caches every page that doesn't have GET or POST
|
2006-07-20 23:45:16 +08:00
|
|
|
parameters. Optionally, if the ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting is
|
2006-07-21 00:06:02 +08:00
|
|
|
``True``, only anonymous requests (i.e., not those made by a logged-in user)
|
2006-07-20 23:45:16 +08:00
|
|
|
will be cached. This is a simple and effective way of disabling caching for any
|
2006-08-18 11:33:37 +08:00
|
|
|
user-specific pages (include Django's admin interface). Note that if you use
|
|
|
|
``CACHE_MIDDLEWARE_ANONYMOUS_ONLY``, you should make sure you've activated
|
2008-08-09 23:07:45 +08:00
|
|
|
``AuthenticationMiddleware``.
|
2006-07-20 23:37:12 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
Additionally, the cache middleware automatically sets a few headers in each
|
2006-07-20 23:45:16 +08:00
|
|
|
``HttpResponse``:
|
2005-07-20 04:49:07 +08:00
|
|
|
|
|
|
|
* Sets the ``Last-Modified`` header to the current date/time when a fresh
|
|
|
|
(uncached) version of the page is requested.
|
2005-10-09 08:55:08 +08:00
|
|
|
* Sets the ``Expires`` header to the current date/time plus the defined
|
|
|
|
``CACHE_MIDDLEWARE_SECONDS``.
|
|
|
|
* Sets the ``Cache-Control`` header to give a max age for the page -- again,
|
|
|
|
from the ``CACHE_MIDDLEWARE_SECONDS`` setting.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
See :ref:`topics-http-middleware` for more on middleware.
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2008-09-02 11:40:42 +08:00
|
|
|
.. versionadded:: 1.0
|
2007-11-30 00:57:18 +08:00
|
|
|
|
|
|
|
If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
|
|
|
|
its ``Cache-Control`` header) then the page will be cached until the expiry
|
|
|
|
time, rather than ``CACHE_MIDDLEWARE_SECONDS``. Using the decorators in
|
|
|
|
``django.views.decorators.cache`` you can easily set a view's expiry time
|
|
|
|
(using the ``cache_control`` decorator) or disable caching for a view (using
|
|
|
|
the ``never_cache`` decorator). See the `using other headers`__ section for
|
|
|
|
more on these decorators.
|
|
|
|
|
|
|
|
__ `Controlling cache: Using other headers`_
|
|
|
|
|
2006-02-19 00:22:31 +08:00
|
|
|
The per-view cache
|
2005-07-20 04:49:07 +08:00
|
|
|
==================
|
|
|
|
|
|
|
|
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::
|
2005-07-16 01:05:43 +08:00
|
|
|
|
|
|
|
from django.views.decorators.cache import cache_page
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
def slashdot_this(request):
|
|
|
|
...
|
2005-07-20 04:49:07 +08:00
|
|
|
|
|
|
|
slashdot_this = cache_page(slashdot_this, 60 * 15)
|
2005-07-16 01:05:43 +08:00
|
|
|
|
|
|
|
Or, using Python 2.4's decorator syntax::
|
|
|
|
|
|
|
|
@cache_page(60 * 15)
|
|
|
|
def slashdot_this(request):
|
|
|
|
...
|
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
``cache_page`` takes a single argument: the cache timeout, in seconds. In the
|
|
|
|
above example, the result of the ``slashdot_this()`` view will be cached for 15
|
|
|
|
minutes.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2007-10-21 23:48:40 +08:00
|
|
|
Template fragment caching
|
|
|
|
=========================
|
|
|
|
|
2008-09-02 11:40:42 +08:00
|
|
|
.. versionadded:: 1.0
|
2007-10-31 09:46:32 +08:00
|
|
|
|
2007-10-21 23:48:40 +08:00
|
|
|
If you're after even more control, you can also cache template fragments using
|
2007-10-31 09:46:32 +08:00
|
|
|
the ``cache`` template tag. To give your template access to this tag, put
|
|
|
|
``{% load cache %}`` near the top of your template.
|
2007-10-21 23:48:40 +08:00
|
|
|
|
|
|
|
The ``{% cache %}`` template tag caches the contents of the block for a given
|
2007-10-31 09:46:32 +08:00
|
|
|
amount of time. It takes at least two arguments: the cache timeout, in seconds,
|
|
|
|
and the name to give the cache fragment. For example::
|
2007-10-21 23:48:40 +08:00
|
|
|
|
|
|
|
{% load cache %}
|
|
|
|
{% cache 500 sidebar %}
|
|
|
|
.. sidebar ..
|
|
|
|
{% endcache %}
|
|
|
|
|
|
|
|
Sometimes you might want to cache multiple copies of a fragment depending on
|
2007-11-30 13:34:04 +08:00
|
|
|
some dynamic data that appears inside the fragment. For example, you might want a
|
2007-10-21 23:48:40 +08:00
|
|
|
separate cached copy of the sidebar used in the previous example for every user
|
2007-11-30 13:34:04 +08:00
|
|
|
of your site. Do this by passing additional arguments to the ``{% cache %}``
|
|
|
|
template tag to uniquely identify the cache fragment::
|
2007-10-21 23:48:40 +08:00
|
|
|
|
|
|
|
{% load cache %}
|
|
|
|
{% cache 500 sidebar request.user.username %}
|
|
|
|
.. sidebar for logged in user ..
|
|
|
|
{% endcache %}
|
|
|
|
|
2007-11-30 13:34:04 +08:00
|
|
|
It's perfectly fine to specify more than one argument to identify the fragment.
|
|
|
|
Simply pass as many arguments to ``{% cache %}`` as you need.
|
2007-10-21 23:48:40 +08:00
|
|
|
|
2008-06-26 12:54:10 +08:00
|
|
|
The cache timeout can be a template variable, as long as the template variable
|
|
|
|
resolves to an integer value. For example, if the template variable
|
|
|
|
``my_timeout`` is set to the value ``600``, then the following two examples are
|
|
|
|
equivalent::
|
|
|
|
|
|
|
|
{% cache 600 sidebar %} ... {% endcache %}
|
|
|
|
{% cache my_timeout sidebar %} ... {% endcache %}
|
|
|
|
|
|
|
|
This feature is useful in avoiding repetition in templates. You can set the
|
|
|
|
timeout in a variable, in one place, and just reuse that value.
|
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
The low-level cache API
|
|
|
|
=======================
|
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
Sometimes, however, caching an entire rendered page doesn't gain you very much.
|
|
|
|
For example, you may find it's only necessary to cache the result of an
|
2006-02-19 00:22:31 +08:00
|
|
|
intensive database query. In cases like this, you can use the low-level cache
|
|
|
|
API to store objects in the cache with any level of granularity you like.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The cache API is simple. The cache module, ``django.core.cache``, exports a
|
|
|
|
``cache`` object that's automatically created from the ``CACHE_BACKEND``
|
|
|
|
setting::
|
2005-07-16 01:05:43 +08:00
|
|
|
|
|
|
|
>>> from django.core.cache import cache
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The basic interface is ``set(key, value, timeout_seconds)`` and ``get(key)``::
|
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
>>> cache.set('my_key', 'hello, world!', 30)
|
|
|
|
>>> cache.get('my_key')
|
|
|
|
'hello, world!'
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
The ``timeout_seconds`` argument is optional and defaults to the ``timeout``
|
|
|
|
argument in the ``CACHE_BACKEND`` setting (explained above).
|
|
|
|
|
|
|
|
If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
|
|
|
|
|
|
|
|
>>> cache.get('some_other_key')
|
|
|
|
None
|
|
|
|
|
|
|
|
# Wait 30 seconds for 'my_key' to expire...
|
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
>>> cache.get('my_key')
|
|
|
|
None
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
get() can take a ``default`` argument::
|
|
|
|
|
|
|
|
>>> cache.get('my_key', 'has expired')
|
|
|
|
'has expired'
|
|
|
|
|
2008-09-02 11:40:42 +08:00
|
|
|
.. versionadded:: 1.0
|
|
|
|
|
|
|
|
To add a key only if it doesn't already exist, use the ``add()`` method.
|
|
|
|
It takes the same parameters as ``set()``, but it will not attempt to
|
|
|
|
update the cache if the key specified is already present::
|
2007-10-20 23:16:34 +08:00
|
|
|
|
|
|
|
>>> cache.set('add_key', 'Initial value')
|
|
|
|
>>> cache.add('add_key', 'New value')
|
|
|
|
>>> cache.get('add_key')
|
|
|
|
'Initial value'
|
|
|
|
|
2008-08-10 11:52:21 +08:00
|
|
|
If you need to know whether ``add()`` stored a value in the cache, you can
|
|
|
|
check the return value. It will return ``True`` if the value was stored,
|
|
|
|
``False`` otherwise.
|
|
|
|
|
|
|
|
There's also a ``get_many()`` interface that only hits the cache once.
|
|
|
|
``get_many()`` returns a dictionary with all the keys you asked for that
|
|
|
|
actually exist in the cache (and haven't expired)::
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
>>> cache.set('a', 1)
|
|
|
|
>>> cache.set('b', 2)
|
|
|
|
>>> cache.set('c', 3)
|
|
|
|
>>> cache.get_many(['a', 'b', 'c'])
|
|
|
|
{'a': 1, 'b': 2, 'c': 3}
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Finally, you can delete keys explicitly with ``delete()``. This is an easy way
|
|
|
|
of clearing the cache for a particular object::
|
|
|
|
|
2005-07-16 01:05:43 +08:00
|
|
|
>>> cache.delete('a')
|
2005-07-20 04:49:07 +08:00
|
|
|
|
2009-03-11 21:27:03 +08:00
|
|
|
.. versionadded:: 1.1
|
|
|
|
|
|
|
|
You can also increment or decrement a key that already exists using the
|
|
|
|
``incr()`` or ``decr()`` methods, respectively. By default, the existing cache
|
|
|
|
value will incremented or decremented by 1. Other increment/decrement values
|
|
|
|
can be specified by providing an argument to the increment/decrement call. A
|
|
|
|
ValueError will be raised if you attempt to increment or decrement a
|
|
|
|
nonexistent cache key.::
|
|
|
|
|
|
|
|
>>> cache.set('num', 1)
|
|
|
|
>>> cache.incr('num')
|
|
|
|
2
|
|
|
|
>>> cache.incr('num', 10)
|
|
|
|
12
|
|
|
|
>>> cache.decr('num')
|
|
|
|
11
|
|
|
|
>>> cache.decr('num', 5)
|
|
|
|
6
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
``incr()``/``decr()`` methods are not guaranteed to be atomic. On those
|
|
|
|
backends that support atomic increment/decrement (most notably, the
|
|
|
|
memcached backend), increment and decrement operations will be atomic.
|
|
|
|
However, if the backend doesn't natively provide an increment/decrement
|
|
|
|
operation, it will be implemented using a 2 step retrieve/update.
|
|
|
|
|
2005-09-01 01:06:07 +08:00
|
|
|
That's it. The cache has very few restrictions: You can cache any object that
|
|
|
|
can be pickled safely, although keys must be strings.
|
2005-07-16 01:05:43 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Upstream caches
|
|
|
|
===============
|
|
|
|
|
|
|
|
So far, this document has focused on caching your *own* data. But another type
|
|
|
|
of caching is relevant to Web development, too: caching performed by "upstream"
|
|
|
|
caches. These are systems that cache pages for users even before the request
|
|
|
|
reaches your Web site.
|
|
|
|
|
|
|
|
Here are a few examples of upstream caches:
|
|
|
|
|
|
|
|
* Your ISP may cache certain pages, so if you requested a page from
|
|
|
|
somedomain.com, your ISP would send you the page without having to access
|
|
|
|
somedomain.com directly.
|
|
|
|
|
2006-05-15 19:28:37 +08:00
|
|
|
* Your Django Web site may sit behind a Squid Web proxy
|
2006-05-02 09:31:56 +08:00
|
|
|
(http://www.squid-cache.org/) that caches pages for performance. In this
|
|
|
|
case, each request first would be handled by Squid, and it'd only be
|
|
|
|
passed to your application if needed.
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
* Your Web browser caches pages, too. If a Web page sends out the right
|
|
|
|
headers, your browser will use the local (cached) copy for subsequent
|
|
|
|
requests to that page.
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Upstream caching is a nice efficiency boost, but there's a danger to it:
|
|
|
|
Many Web pages' contents differ based on authentication and a host of other
|
|
|
|
variables, and cache systems that blindly save pages based purely on URLs could
|
|
|
|
expose incorrect or sensitive data to subsequent visitors to those pages.
|
|
|
|
|
|
|
|
For example, say you operate a Web e-mail system, and the contents of the
|
|
|
|
"inbox" page obviously depend on which user is logged in. If an ISP blindly
|
|
|
|
cached your site, then the first user who logged in through that ISP would have
|
|
|
|
his user-specific inbox page cached for subsequent visitors to the site. That's
|
|
|
|
not cool.
|
|
|
|
|
|
|
|
Fortunately, HTTP provides a solution to this problem: A set of HTTP headers
|
|
|
|
exist to instruct caching mechanisms to differ their cache contents depending
|
|
|
|
on designated variables, and to tell caching mechanisms not to cache particular
|
|
|
|
pages.
|
|
|
|
|
|
|
|
Using Vary headers
|
|
|
|
==================
|
|
|
|
|
|
|
|
One of these headers is ``Vary``. It defines which request headers a cache
|
|
|
|
mechanism should take into account when building its cache key. For example, if
|
|
|
|
the contents of a Web page depend on a user's language preference, the page is
|
|
|
|
said to "vary on language."
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
By default, Django's cache system creates its cache keys using the requested
|
|
|
|
path -- e.g., ``"/stories/2005/jun/23/bank_robbed/"``. This means every request
|
|
|
|
to that URL will use the same cached version, regardless of user-agent
|
|
|
|
differences such as cookies or language preferences.
|
|
|
|
|
|
|
|
That's where ``Vary`` comes in.
|
|
|
|
|
|
|
|
If your Django-powered page outputs different content based on some difference
|
|
|
|
in request headers -- such as a cookie, or language, or user-agent -- you'll
|
|
|
|
need to use the ``Vary`` header to tell caching mechanisms that the page output
|
|
|
|
depends on those things.
|
|
|
|
|
|
|
|
To do this in Django, use the convenient ``vary_on_headers`` view decorator,
|
|
|
|
like so::
|
|
|
|
|
|
|
|
from django.views.decorators.vary import vary_on_headers
|
|
|
|
|
|
|
|
# Python 2.3 syntax.
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
my_view = vary_on_headers(my_view, 'User-Agent')
|
|
|
|
|
|
|
|
# Python 2.4 decorator syntax.
|
|
|
|
@vary_on_headers('User-Agent')
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
|
|
|
In this case, a caching mechanism (such as Django's own cache middleware) will
|
|
|
|
cache a separate version of the page for each unique user-agent.
|
|
|
|
|
|
|
|
The advantage to using the ``vary_on_headers`` decorator rather than manually
|
|
|
|
setting the ``Vary`` header (using something like
|
|
|
|
``response['Vary'] = 'user-agent'``) is that the decorator adds to the ``Vary``
|
|
|
|
header (which may already exist) rather than setting it from scratch.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
You can pass multiple headers to ``vary_on_headers()``::
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
@vary_on_headers('User-Agent', 'Cookie')
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
|
|
|
Because varying on cookie is such a common case, there's a ``vary_on_cookie``
|
|
|
|
decorator. These two views are equivalent::
|
|
|
|
|
|
|
|
@vary_on_cookie
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
|
|
|
@vary_on_headers('Cookie')
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
|
|
|
Also note that the headers you pass to ``vary_on_headers`` are not case
|
|
|
|
sensitive. ``"User-Agent"`` is the same thing as ``"user-agent"``.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
You can also use a helper function, ``django.utils.cache.patch_vary_headers``,
|
|
|
|
directly::
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
from django.utils.cache import patch_vary_headers
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
response = render_to_response('template_name', context)
|
|
|
|
patch_vary_headers(response, ['Cookie'])
|
|
|
|
return response
|
|
|
|
|
|
|
|
``patch_vary_headers`` takes an ``HttpResponse`` instance as its first argument
|
|
|
|
and a list/tuple of header names as its second argument.
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
For more on Vary headers, see the `official Vary spec`_.
|
|
|
|
|
|
|
|
.. _`official Vary spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
Controlling cache: Using other headers
|
|
|
|
======================================
|
|
|
|
|
|
|
|
Another problem with caching is the privacy of data and the question of where
|
|
|
|
data should be stored in a cascade of caches.
|
|
|
|
|
|
|
|
A user usually faces two kinds of caches: his own browser cache (a private
|
|
|
|
cache) and his provider's cache (a public cache). A public cache is used by
|
|
|
|
multiple users and controlled by someone else. This poses problems with
|
|
|
|
sensitive data: You don't want, say, your banking-account number stored in a
|
|
|
|
public cache. So Web applications need a way to tell caches which data is
|
|
|
|
private and which is public.
|
|
|
|
|
|
|
|
The solution is to indicate a page's cache should be "private." To do this in
|
|
|
|
Django, use the ``cache_control`` view decorator. Example::
|
|
|
|
|
|
|
|
from django.views.decorators.cache import cache_control
|
|
|
|
@cache_control(private=True)
|
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
|
|
|
This decorator takes care of sending out the appropriate HTTP header behind the
|
|
|
|
scenes.
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
There are a few other ways to control cache parameters. For example, HTTP
|
|
|
|
allows applications to do the following:
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
* Define the maximum time a page should be cached.
|
|
|
|
* Specify whether a cache should always check for newer versions, only
|
|
|
|
delivering the cached content when there are no changes. (Some caches
|
|
|
|
might deliver cached content even if the server page changed -- simply
|
|
|
|
because the cache copy isn't yet expired.)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
In Django, use the ``cache_control`` view decorator to specify these cache
|
2005-10-31 11:17:39 +08:00
|
|
|
parameters. In this example, ``cache_control`` tells caches to revalidate the
|
|
|
|
cache on every access and to store cached versions for, at most, 3600 seconds::
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
from django.views.decorators.cache import cache_control
|
|
|
|
@cache_control(must_revalidate=True, max_age=3600)
|
2005-10-30 01:00:20 +08:00
|
|
|
def my_view(request):
|
|
|
|
...
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
|
|
|
|
Here's a full list:
|
2005-10-31 11:14:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
* ``public=True``
|
|
|
|
* ``private=True``
|
|
|
|
* ``no_cache=True``
|
|
|
|
* ``no_transform=True``
|
|
|
|
* ``must_revalidate=True``
|
|
|
|
* ``proxy_revalidate=True``
|
|
|
|
* ``max_age=num_seconds``
|
|
|
|
* ``s_maxage=num_seconds``
|
2005-10-31 11:14:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
(Note that the caching middleware already sets the cache header's max-age with
|
|
|
|
the value of the ``CACHE_MIDDLEWARE_SETTINGS`` setting. If you use a custom
|
|
|
|
``max_age`` in a ``cache_control`` decorator, the decorator will take
|
|
|
|
precedence, and the header values will be merged correctly.)
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2007-10-21 20:12:45 +08:00
|
|
|
If you want to use headers to disable caching altogether,
|
2007-11-30 00:57:18 +08:00
|
|
|
``django.views.decorators.cache.never_cache`` is a view decorator that adds
|
2007-09-16 02:43:49 +08:00
|
|
|
headers to ensure the response won't be cached by browsers or other caches. Example::
|
|
|
|
|
|
|
|
from django.views.decorators.cache import never_cache
|
|
|
|
@never_cache
|
|
|
|
def myview(request):
|
|
|
|
...
|
|
|
|
|
2005-10-31 11:14:57 +08:00
|
|
|
.. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
|
2005-10-30 01:00:20 +08:00
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
Other optimizations
|
|
|
|
===================
|
|
|
|
|
|
|
|
Django comes with a few other pieces of middleware that can help optimize your
|
|
|
|
apps' performance:
|
|
|
|
|
|
|
|
* ``django.middleware.http.ConditionalGetMiddleware`` adds support for
|
|
|
|
conditional GET. This makes use of ``ETag`` and ``Last-Modified``
|
|
|
|
headers.
|
|
|
|
|
|
|
|
* ``django.middleware.gzip.GZipMiddleware`` compresses content for browsers
|
|
|
|
that understand gzip compression (all modern browsers).
|
|
|
|
|
|
|
|
Order of MIDDLEWARE_CLASSES
|
|
|
|
===========================
|
|
|
|
|
2008-08-15 19:52:18 +08:00
|
|
|
If you use caching middleware, it's important to put each half in the right
|
2008-08-09 23:07:45 +08:00
|
|
|
place within the ``MIDDLEWARE_CLASSES`` setting. That's because the cache
|
|
|
|
middleware needs to know which headers by which to vary the cache storage.
|
|
|
|
Middleware always adds something to the ``Vary`` response header when it can.
|
2005-10-09 08:55:08 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
``UpdateCacheMiddleware`` runs during the response phase, where middleware is
|
|
|
|
run in reverse order, so an item at the top of the list runs *last* during the
|
|
|
|
response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
|
|
|
|
appears *before* any other middleware that might add something to the ``Vary``
|
|
|
|
header. The following middleware modules do so:
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
* ``SessionMiddleware`` adds ``Cookie``
|
2005-10-09 09:02:30 +08:00
|
|
|
* ``GZipMiddleware`` adds ``Accept-Encoding``
|
2007-10-21 20:12:45 +08:00
|
|
|
* ``LocaleMiddleware`` adds ``Accept-Language``
|
2008-08-15 22:17:24 +08:00
|
|
|
|
2008-08-09 23:07:45 +08:00
|
|
|
``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
|
|
|
|
where middleware is applied first-to-last, so an item at the top of the list
|
|
|
|
runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
|
|
|
|
needs to run after other middleware updates the ``Vary`` header, so
|
|
|
|
``FetchFromCacheMiddleware`` must be *after* any item that does so.
|
2007-10-21 20:12:45 +08:00
|
|
|
|