| 1 |
======================== |
| 2 |
Django's cache framework |
| 3 |
======================== |
| 4 |
|
| 5 |
A fundamental trade-off in dynamic websites is, well, they're dynamic. Each |
| 6 |
time a user requests a page, the web server makes all sorts of calculations -- |
| 7 |
from database queries to template rendering to business logic -- to create the |
| 8 |
page that your site's visitor sees. This is a lot more expensive, from a |
| 9 |
processing-overhead perspective, than your standard |
| 10 |
read-a-file-off-the-filesystem server arrangement. |
| 11 |
|
| 12 |
For most web applications, this overhead isn't a big deal. Most web |
| 13 |
applications aren't ``washingtonpost.com`` or ``slashdot.org``; they're small- |
| 14 |
to medium-sized sites with so-so traffic. But for medium- to high-traffic |
| 15 |
sites, it's essential to cut as much overhead as possible. |
| 16 |
|
| 17 |
That's where caching comes in. |
| 18 |
|
| 19 |
To cache something is to save the result of an expensive calculation so that |
| 20 |
you don't have to perform the calculation next time. Here's some pseudocode |
| 21 |
explaining how this would work for a dynamically generated web page: |
| 22 |
|
| 23 |
.. code-block:: text |
| 24 |
|
| 25 |
given a URL, try finding that page in the cache |
| 26 |
if the page is in the cache: |
| 27 |
return the cached page |
| 28 |
else: |
| 29 |
generate the page |
| 30 |
save the generated page in the cache (for next time) |
| 31 |
return the generated page |
| 32 |
|
| 33 |
Django comes with a robust cache system that lets you save dynamic pages so |
| 34 |
they don't have to be calculated for each request. For convenience, Django |
| 35 |
offers different levels of cache granularity: You can cache the output of |
| 36 |
specific views, you can cache only the pieces that are difficult to produce, |
| 37 |
or you can cache your entire site. |
| 38 |
|
| 39 |
Django also works well with "downstream" caches, such as `Squid |
| 40 |
<http://www.squid-cache.org/>`_ and browser-based caches. These are the types |
| 41 |
of caches that you don't directly control but to which you can provide hints |
| 42 |
(via HTTP headers) about which parts of your site should be cached, and how. |
| 43 |
|
| 44 |
.. seealso:: |
| 45 |
The :ref:`Cache Framework design philosophy <cache-design-philosophy>` |
| 46 |
explains a few of the design decisions of the framework. |
| 47 |
|
| 48 |
.. _setting-up-the-cache: |
| 49 |
|
| 50 |
Setting up the cache |
| 51 |
==================== |
| 52 |
|
| 53 |
The cache system requires a small amount of setup. Namely, you have to tell it |
| 54 |
where your cached data should live -- whether in a database, on the filesystem |
| 55 |
or directly in memory. This is an important decision that affects your cache's |
| 56 |
performance; yes, some cache types are faster than others. |
| 57 |
|
| 58 |
Your cache preference goes in the :setting:`CACHES` setting in your |
| 59 |
settings file. Here's an explanation of all available values for |
| 60 |
:setting:`CACHES`. |
| 61 |
|
| 62 |
.. _memcached: |
| 63 |
|
| 64 |
Memcached |
| 65 |
--------- |
| 66 |
|
| 67 |
Memcached__ is an entirely memory-based cache server, originally developed |
| 68 |
to handle high loads at LiveJournal.com and subsequently open-sourced by |
| 69 |
Danga Interactive. It is used by sites such as Facebook and Wikipedia to |
| 70 |
reduce database access and dramatically increase site performance. |
| 71 |
|
| 72 |
__ https://memcached.org/ |
| 73 |
|
| 74 |
Memcached runs as a daemon and is allotted a specified amount of RAM. All it |
| 75 |
does is provide a fast interface for adding, retrieving and deleting data in |
| 76 |
the cache. All data is stored directly in memory, so there's no overhead of |
| 77 |
database or filesystem usage. |
| 78 |
|
| 79 |
After installing Memcached itself, you'll need to install a Memcached |
| 80 |
binding. There are several Python Memcached bindings available; the |
| 81 |
two supported by Django are :pypi:`pylibmc` and :pypi:`pymemcache`. |
| 82 |
|
| 83 |
To use Memcached with Django: |
| 84 |
|
| 85 |
* Set :setting:`BACKEND <CACHES-BACKEND>` to |
| 86 |
``django.core.cache.backends.memcached.PyMemcacheCache`` or |
| 87 |
``django.core.cache.backends.memcached.PyLibMCCache`` (depending on your |
| 88 |
chosen memcached binding) |
| 89 |
|
| 90 |
* Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values, |
| 91 |
where ``ip`` is the IP address of the Memcached daemon and ``port`` is the |
| 92 |
port on which Memcached is running, or to a ``unix:path`` value, where |
| 93 |
``path`` is the path to a Memcached Unix socket file. |
| 94 |
|
| 95 |
In this example, Memcached is running on localhost (127.0.0.1) port 11211, using |
| 96 |
the ``pymemcache`` binding:: |
| 97 |
|
| 98 |
CACHES = { |
| 99 |
"default": { |
| 100 |
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", |
| 101 |
"LOCATION": "127.0.0.1:11211", |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
In this example, Memcached is available through a local Unix socket file |
| 106 |
:file:`/tmp/memcached.sock` using the ``pymemcache`` binding:: |
| 107 |
|
| 108 |
CACHES = { |
| 109 |
"default": { |
| 110 |
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", |
| 111 |
"LOCATION": "unix:/tmp/memcached.sock", |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
One excellent feature of Memcached is its ability to share a cache over |
| 116 |
multiple servers. This means you can run Memcached daemons on multiple |
| 117 |
machines, and the program will treat the group of machines as a *single* |
| 118 |
cache, without the need to duplicate cache values on each machine. To take |
| 119 |
advantage of this feature, include all server addresses in |
| 120 |
:setting:`LOCATION <CACHES-LOCATION>`, either as a semicolon or comma |
| 121 |
delimited string, or as a list. |
| 122 |
|
| 123 |
In this example, the cache is shared over Memcached instances running on IP |
| 124 |
address 172.19.26.240 and 172.19.26.242, both on port 11211:: |
| 125 |
|
| 126 |
CACHES = { |
| 127 |
"default": { |
| 128 |
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", |
| 129 |
"LOCATION": [ |
| 130 |
"172.19.26.240:11211", |
| 131 |
"172.19.26.242:11211", |
| 132 |
], |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
In the following example, the cache is shared over Memcached instances running |
| 137 |
on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and |
| 138 |
172.19.26.244 (port 11213):: |
| 139 |
|
| 140 |
CACHES = { |
| 141 |
"default": { |
| 142 |
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", |
| 143 |
"LOCATION": [ |
| 144 |
"172.19.26.240:11211", |
| 145 |
"172.19.26.242:11212", |
| 146 |
"172.19.26.244:11213", |
| 147 |
], |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
By default, the ``PyMemcacheCache`` backend sets the following options (you can |
| 152 |
override them in your :setting:`OPTIONS <CACHES-OPTIONS>`):: |
| 153 |
|
| 154 |
"OPTIONS": { |
| 155 |
"allow_unicode_keys": True, |
| 156 |
"default_noreply": False, |
| 157 |
"serde": pymemcache.serde.pickle_serde, |
| 158 |
} |
| 159 |
|
| 160 |
A final point about Memcached is that memory-based caching has a |
| 161 |
disadvantage: because the cached data is stored in memory, the data will be |
| 162 |
lost if your server crashes. Clearly, memory isn't intended for permanent data |
| 163 |
storage, so don't rely on memory-based caching as your only data storage. |
| 164 |
Without a doubt, *none* of the Django caching backends should be used for |
| 165 |
permanent storage -- they're all intended to be solutions for caching, not |
| 166 |
storage -- but we point this out here because memory-based caching is |
| 167 |
particularly temporary. |
| 168 |
|
| 169 |
.. _redis: |
| 170 |
|
| 171 |
Redis |
| 172 |
----- |
| 173 |
|
| 174 |
Redis__ is an in-memory database that can be used for caching. To begin you'll |
| 175 |
need a Redis server running either locally or on a remote machine. |
| 176 |
|
| 177 |
__ https://redis.io/ |
| 178 |
|
| 179 |
After setting up the Redis server, you'll need to install Python bindings for |
| 180 |
Redis. :pypi:`redis-py <redis>` is the binding supported natively by Django. |
| 181 |
Installing the :pypi:`hiredis-py <hiredis>` package is also recommended. |
| 182 |
|
| 183 |
To use Redis as your cache backend with Django: |
| 184 |
|
| 185 |
* Set :setting:`BACKEND <CACHES-BACKEND>` to |
| 186 |
``django.core.cache.backends.redis.RedisCache``. |
| 187 |
|
| 188 |
* Set :setting:`LOCATION <CACHES-LOCATION>` to the URL pointing to your Redis |
| 189 |
instance, using the appropriate scheme. See the ``redis-py`` docs for |
| 190 |
`details on the available schemes |
| 191 |
<https://redis.readthedocs.io/en/stable/connections.html#redis.connection.ConnectionPool.from_url>`__. |
| 192 |
|
| 193 |
For example, if Redis is running on localhost (127.0.0.1) port 6379:: |
| 194 |
|
| 195 |
CACHES = { |
| 196 |
"default": { |
| 197 |
"BACKEND": "django.core.cache.backends.redis.RedisCache", |
| 198 |
"LOCATION": "redis://127.0.0.1:6379", |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
Often Redis servers are protected with authentication. In order to supply a |
| 203 |
username and password, add them in the ``LOCATION`` along with the URL:: |
| 204 |
|
| 205 |
CACHES = { |
| 206 |
"default": { |
| 207 |
"BACKEND": "django.core.cache.backends.redis.RedisCache", |
| 208 |
"LOCATION": "redis://username:[email protected]:6379", |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
If you have multiple Redis servers set up in the replication mode, you can |
| 213 |
specify the servers either as a semicolon or comma delimited string, or as a |
| 214 |
list. While using multiple servers, write operations are performed on the first |
| 215 |
server (leader). Read operations are performed on the other servers (replicas) |
| 216 |
chosen at random:: |
| 217 |
|
| 218 |
CACHES = { |
| 219 |
"default": { |
| 220 |
"BACKEND": "django.core.cache.backends.redis.RedisCache", |
| 221 |
"LOCATION": [ |
| 222 |
"redis://127.0.0.1:6379", # leader |
| 223 |
"redis://127.0.0.1:6378", # read-replica 1 |
| 224 |
"redis://127.0.0.1:6377", # read-replica 2 |
| 225 |
], |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
.. _database-caching: |
| 230 |
|
| 231 |
Database caching |
| 232 |
---------------- |
| 233 |
|
| 234 |
Django can store its cached data in your database. This works best if you've |
| 235 |
got a fast, well-indexed database server. |
| 236 |
|
| 237 |
To use a database table as your cache backend: |
| 238 |
|
| 239 |
* Set :setting:`BACKEND <CACHES-BACKEND>` to |
| 240 |
``django.core.cache.backends.db.DatabaseCache`` |
| 241 |
|
| 242 |
* Set :setting:`LOCATION <CACHES-LOCATION>` to ``tablename``, the name of the |
| 243 |
database table. This name can be whatever you want, as long as it's a valid |
| 244 |
table name that's not already being used in your database. |
| 245 |
|
| 246 |
In this example, the cache table's name is ``my_cache_table``:: |
| 247 |
|
| 248 |
CACHES = { |
| 249 |
"default": { |
| 250 |
"BACKEND": "django.core.cache.backends.db.DatabaseCache", |
| 251 |
"LOCATION": "my_cache_table", |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
Unlike other cache backends, the database cache does not support automatic |
| 256 |
culling of expired entries at the database level. Instead, expired cache |
| 257 |
entries are culled each time ``add()``, ``set()``, or ``touch()`` is called. |
| 258 |
|
| 259 |
.. _database-caching-creating-the-table: |
| 260 |
|
| 261 |
Creating the cache table |
| 262 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 263 |
|
| 264 |
Before using the database cache, you must create the cache table with this |
| 265 |
command: |
| 266 |
|
| 267 |
.. code-block:: shell |
| 268 |
|
| 269 |
python manage.py createcachetable |
| 270 |
|
| 271 |
This creates a table in your database that is in the proper format that |
| 272 |
Django's database-cache system expects. The name of the table is taken from |
| 273 |
:setting:`LOCATION <CACHES-LOCATION>`. |
| 274 |
|
| 275 |
If you are using multiple database caches, :djadmin:`createcachetable` creates |
| 276 |
one table for each cache. |
| 277 |
|
| 278 |
If you are using multiple databases, :djadmin:`createcachetable` observes the |
| 279 |
``allow_migrate()`` method of your database routers (see below). |
| 280 |
|
| 281 |
Like :djadmin:`migrate`, :djadmin:`createcachetable` won't touch an existing |
| 282 |
table. It will only create missing tables. |
| 283 |
|
| 284 |
To print the SQL that would be run, rather than run it, use the |
| 285 |
:option:`createcachetable --dry-run` option. |
| 286 |
|
| 287 |
.. _database-caching-multiple-databases: |
| 288 |
|
| 289 |
Multiple databases |
| 290 |
~~~~~~~~~~~~~~~~~~ |
| 291 |
|
| 292 |
If you use database caching with multiple databases, you'll also need |
| 293 |
to set up routing instructions for your database cache table. For the |
| 294 |
purposes of routing, the database cache table appears as a model named |
| 295 |
``CacheEntry``, in an application named ``django_cache``. This model |
| 296 |
won't appear in the models cache, but the model details can be used |
| 297 |
for routing purposes. |
| 298 |
|
| 299 |
For example, the following router would direct all cache read |
| 300 |
operations to ``cache_replica``, and all write operations to |
| 301 |
``cache_primary``. The cache table will only be synchronized onto |
| 302 |
``cache_primary``:: |
| 303 |
|
| 304 |
class CacheRouter: |
| 305 |
"""A router to control all database cache operations""" |
| 306 |
|
| 307 |
def db_for_read(self, model, **hints): |
| 308 |
"All cache read operations go to the replica" |
| 309 |
if model._meta.app_label == "django_cache": |
| 310 |
return "cache_replica" |
| 311 |
return None |
| 312 |
|
| 313 |
def db_for_write(self, model, **hints): |
| 314 |
"All cache write operations go to primary" |
| 315 |
if model._meta.app_label == "django_cache": |
| 316 |
return "cache_primary" |
| 317 |
return None |
| 318 |
|
| 319 |
def allow_migrate(self, db, app_label, model_name=None, **hints): |
| 320 |
"Only install the cache model on primary" |
| 321 |
if app_label == "django_cache": |
| 322 |
return db == "cache_primary" |
| 323 |
return None |
| 324 |
|
| 325 |
If you don't specify routing directions for the database cache model, |
| 326 |
the cache backend will use the ``default`` database. |
| 327 |
|
| 328 |
And if you don't use the database cache backend, you don't need to worry about |
| 329 |
providing routing instructions for the database cache model. |
| 330 |
|
| 331 |
.. _filesystem-caching: |
| 332 |
|
| 333 |
Filesystem caching |
| 334 |
------------------ |
| 335 |
|
| 336 |
The file-based backend serializes and stores each cache value as a separate |
| 337 |
file. To use this backend set :setting:`BACKEND <CACHES-BACKEND>` to |
| 338 |
``"django.core.cache.backends.filebased.FileBasedCache"`` and |
| 339 |
:setting:`LOCATION <CACHES-LOCATION>` to a suitable directory. For example, |
| 340 |
to store cached data in ``/var/tmp/django_cache``, use this setting:: |
| 341 |
|
| 342 |
CACHES = { |
| 343 |
"default": { |
| 344 |
"BACKEND": "django.core.cache.backends.filebased.FileBasedCache", |
| 345 |
"LOCATION": "/var/tmp/django_cache", |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
If you're on Windows, put the drive letter at the beginning of the path, |
| 350 |
like this:: |
| 351 |
|
| 352 |
CACHES = { |
| 353 |
"default": { |
| 354 |
"BACKEND": "django.core.cache.backends.filebased.FileBasedCache", |
| 355 |
"LOCATION": "c:/foo/bar", |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
The directory path should be absolute -- that is, it should start at the root |
| 360 |
of your filesystem. It doesn't matter whether you put a slash at the end of the |
| 361 |
setting. |
| 362 |
|
| 363 |
Make sure the directory pointed-to by this setting either exists and is |
| 364 |
readable and writable, or that it can be created by the system user under which |
| 365 |
your web server runs. Continuing the above example, if your server runs as the |
| 366 |
user ``apache``, make sure the directory ``/var/tmp/django_cache`` exists and |
| 367 |
is readable and writable by the user ``apache``, or that it can be created by |
| 368 |
the user ``apache``. |
| 369 |
|
| 370 |
.. warning:: |
| 371 |
|
| 372 |
When the cache :setting:`LOCATION <CACHES-LOCATION>` is contained within |
| 373 |
:setting:`MEDIA_ROOT`, :setting:`STATIC_ROOT`, or |
| 374 |
:setting:`STATICFILES_FINDERS`, sensitive data may be exposed. |
| 375 |
|
| 376 |
An attacker who gains access to the cache file can not only falsify HTML |
| 377 |
content, which your site will trust, but also remotely execute arbitrary |
| 378 |
code, as the data is serialized using :mod:`pickle`. |
| 379 |
|
| 380 |
.. warning:: |
| 381 |
|
| 382 |
Filesystem caching may become slow when storing a large number of files. If |
| 383 |
you run into this problem, consider using a different caching mechanism. |
| 384 |
You can also subclass |
| 385 |
:source:`FileBasedCache <django/core/cache/backends/filebased.py>` and |
| 386 |
improve the culling strategy. |
| 387 |
|
| 388 |
.. _local-memory-caching: |
| 389 |
|
| 390 |
Local-memory caching |
| 391 |
-------------------- |
| 392 |
|
| 393 |
This is the default cache if another is not specified in your settings file. If |
| 394 |
you want the speed advantages of in-memory caching but don't have the capability |
| 395 |
of running Memcached, consider the local-memory cache backend. This cache is |
| 396 |
per-process (see below) and thread-safe. To use it, set :setting:`BACKEND |
| 397 |
<CACHES-BACKEND>` to ``"django.core.cache.backends.locmem.LocMemCache"``. For |
| 398 |
example:: |
| 399 |
|
| 400 |
CACHES = { |
| 401 |
"default": { |
| 402 |
"BACKEND": "django.core.cache.backends.locmem.LocMemCache", |
| 403 |
"LOCATION": "unique-snowflake", |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
The cache :setting:`LOCATION <CACHES-LOCATION>` is used to identify individual |
| 408 |
memory stores. If you only have one ``locmem`` cache, you can omit the |
| 409 |
:setting:`LOCATION <CACHES-LOCATION>`; however, if you have more than one local |
| 410 |
memory cache, you will need to assign a name to at least one of them in |
| 411 |
order to keep them separate. |
| 412 |
|
| 413 |
The cache uses a least-recently-used (LRU) culling strategy. |
| 414 |
|
| 415 |
Note that each process will have its own private cache instance, which means no |
| 416 |
cross-process caching is possible. This also means the local memory cache isn't |
| 417 |
particularly memory-efficient, so it's probably not a good choice for |
| 418 |
production environments. It's nice for development. |
| 419 |
|
| 420 |
.. _dummy-caching: |
| 421 |
|
| 422 |
Dummy caching (for development) |
| 423 |
------------------------------- |
| 424 |
|
| 425 |
Finally, Django comes with a "dummy" cache that doesn't actually cache -- it |
| 426 |
just implements the cache interface without doing anything. |
| 427 |
|
| 428 |
This is useful if you have a production site that uses heavy-duty caching in |
| 429 |
various places but a development/test environment where you don't want to cache |
| 430 |
and don't want to have to change your code to special-case the latter. To |
| 431 |
activate dummy caching, set :setting:`BACKEND <CACHES-BACKEND>` like so:: |
| 432 |
|
| 433 |
CACHES = { |
| 434 |
"default": { |
| 435 |
"BACKEND": "django.core.cache.backends.dummy.DummyCache", |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
.. _using-a-custom-cache-backend: |
| 440 |
|
| 441 |
Using a custom cache backend |
| 442 |
---------------------------- |
| 443 |
|
| 444 |
While Django includes support for a number of cache backends out-of-the-box, |
| 445 |
sometimes you might want to use a customized cache backend. To use an external |
| 446 |
cache backend with Django, use the Python import path as the |
| 447 |
:setting:`BACKEND <CACHES-BACKEND>` of the :setting:`CACHES` setting, like so:: |
| 448 |
|
| 449 |
CACHES = { |
| 450 |
"default": { |
| 451 |
"BACKEND": "path.to.backend", |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
If you're building your own backend, you can use the standard cache backends |
| 456 |
as reference implementations. You'll find the code in the |
| 457 |
:source:`django/core/cache/backends/` directory of the Django source. |
| 458 |
|
| 459 |
Note: Without a really compelling reason, such as a host that doesn't support |
| 460 |
them, you should stick to the cache backends included with Django. They've |
| 461 |
been well-tested and are well-documented. |
| 462 |
|
| 463 |
.. _cache_arguments: |
| 464 |
|
| 465 |
Cache arguments |
| 466 |
--------------- |
| 467 |
|
| 468 |
Each cache backend can be given additional arguments to control caching |
| 469 |
behavior. These arguments are provided as additional keys in the |
| 470 |
:setting:`CACHES` setting. Valid arguments are as follows: |
| 471 |
|
| 472 |
* :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in |
| 473 |
seconds, to use for the cache. This argument defaults to ``300`` seconds (5 minutes). |
| 474 |
You can set ``TIMEOUT`` to ``None`` so that, by default, cache keys never |
| 475 |
expire. A value of ``0`` causes keys to immediately expire (effectively |
| 476 |
"don't cache"). |
| 477 |
|
| 478 |
* :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be |
| 479 |
passed to the cache backend. The list of valid options will vary |
| 480 |
with each backend, and cache backends backed by a third-party library |
| 481 |
will pass their options directly to the underlying cache library. |
| 482 |
|
| 483 |
Cache backends that implement their own culling strategy (i.e., |
| 484 |
the ``locmem``, ``filesystem`` and ``database`` backends) will |
| 485 |
honor the following options: |
| 486 |
|
| 487 |
* ``MAX_ENTRIES``: The maximum number of entries allowed in |
| 488 |
the cache before old values are deleted. This argument |
| 489 |
defaults to ``300``. |
| 490 |
|
| 491 |
* ``CULL_FREQUENCY``: The fraction of entries that are culled |
| 492 |
when ``MAX_ENTRIES`` is reached. The actual ratio is |
| 493 |
``1 / CULL_FREQUENCY``, so set ``CULL_FREQUENCY`` to ``2`` to |
| 494 |
cull half the entries when ``MAX_ENTRIES`` is reached. This argument |
| 495 |
should be an integer and defaults to ``3``. |
| 496 |
|
| 497 |
A value of ``0`` for ``CULL_FREQUENCY`` means that the |
| 498 |
entire cache will be dumped when ``MAX_ENTRIES`` is reached. |
| 499 |
On some backends (``database`` in particular) this makes culling *much* |
| 500 |
faster at the expense of more cache misses. |
| 501 |
|
| 502 |
The Memcached and Redis backends pass the contents of :setting:`OPTIONS |
| 503 |
<CACHES-OPTIONS>` as keyword arguments to the client constructors, allowing |
| 504 |
for more advanced control of client behavior. For example usage, see below. |
| 505 |
|
| 506 |
* :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be |
| 507 |
automatically included (prepended by default) to all cache keys |
| 508 |
used by the Django server. |
| 509 |
|
| 510 |
See the :ref:`cache documentation <cache_key_prefixing>` for |
| 511 |
more information. |
| 512 |
|
| 513 |
* :setting:`VERSION <CACHES-VERSION>`: The default version number |
| 514 |
for cache keys generated by the Django server. |
| 515 |
|
| 516 |
See the :ref:`cache documentation <cache_versioning>` for more |
| 517 |
information. |
| 518 |
|
| 519 |
* :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` |
| 520 |
A string containing a dotted path to a function that defines how |
| 521 |
to compose a prefix, version and key into a final cache key. |
| 522 |
|
| 523 |
See the :ref:`cache documentation <cache_key_transformation>` |
| 524 |
for more information. |
| 525 |
|
| 526 |
In this example, a filesystem backend is being configured with a timeout |
| 527 |
of 60 seconds, and a maximum capacity of 1000 items:: |
| 528 |
|
| 529 |
CACHES = { |
| 530 |
"default": { |
| 531 |
"BACKEND": "django.core.cache.backends.filebased.FileBasedCache", |
| 532 |
"LOCATION": "/var/tmp/django_cache", |
| 533 |
"TIMEOUT": 60, |
| 534 |
"OPTIONS": {"MAX_ENTRIES": 1000}, |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
Here's an example configuration for a ``pylibmc`` based backend that enables |
| 539 |
the binary protocol, SASL authentication, and the ``ketama`` behavior mode:: |
| 540 |
|
| 541 |
CACHES = { |
| 542 |
"default": { |
| 543 |
"BACKEND": "django.core.cache.backends.memcached.PyLibMCCache", |
| 544 |
"LOCATION": "127.0.0.1:11211", |
| 545 |
"OPTIONS": { |
| 546 |
"binary": True, |
| 547 |
"username": "user", |
| 548 |
"password": "pass", |
| 549 |
"behaviors": { |
| 550 |
"ketama": True, |
| 551 |
}, |
| 552 |
}, |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
Here's an example configuration for a ``pymemcache`` based backend that enables |
| 557 |
client pooling (which may improve performance by keeping clients connected), |
| 558 |
treats memcache/network errors as cache misses, and sets the ``TCP_NODELAY`` |
| 559 |
flag on the connection's socket:: |
| 560 |
|
| 561 |
CACHES = { |
| 562 |
"default": { |
| 563 |
"BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", |
| 564 |
"LOCATION": "127.0.0.1:11211", |
| 565 |
"OPTIONS": { |
| 566 |
"no_delay": True, |
| 567 |
"ignore_exc": True, |
| 568 |
"max_pool_size": 4, |
| 569 |
"use_pooling": True, |
| 570 |
}, |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
Here's an example configuration for a ``redis`` based backend that selects |
| 575 |
database ``10`` (by default Redis ships with 16 logical databases), and sets a |
| 576 |
custom `connection pool class`_ (``redis.ConnectionPool`` is used by default):: |
| 577 |
|
| 578 |
CACHES = { |
| 579 |
"default": { |
| 580 |
"BACKEND": "django.core.cache.backends.redis.RedisCache", |
| 581 |
"LOCATION": "redis://127.0.0.1:6379", |
| 582 |
"OPTIONS": { |
| 583 |
"db": "10", |
| 584 |
"pool_class": "redis.BlockingConnectionPool", |
| 585 |
}, |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
.. _`connection pool class`: https://github.com/redis/redis-py#connection-pools |
| 590 |
|
| 591 |
.. _the-per-site-cache: |
| 592 |
|
| 593 |
The per-site cache |
| 594 |
================== |
| 595 |
|
| 596 |
Once the cache is set up, the simplest way to use caching is to cache your |
| 597 |
entire site. You'll need to add |
| 598 |
``'django.middleware.cache.UpdateCacheMiddleware'`` and |
| 599 |
``'django.middleware.cache.FetchFromCacheMiddleware'`` to your |
| 600 |
:setting:`MIDDLEWARE` setting, as in this example:: |
| 601 |
|
| 602 |
MIDDLEWARE = [ |
| 603 |
"django.middleware.cache.UpdateCacheMiddleware", |
| 604 |
"django.middleware.common.CommonMiddleware", |
| 605 |
"django.middleware.cache.FetchFromCacheMiddleware", |
| 606 |
] |
| 607 |
|
| 608 |
.. note:: |
| 609 |
|
| 610 |
No, that's not a typo: the "update" middleware must be first in the list, |
| 611 |
and the "fetch" middleware must be last. The details are a bit obscure, but |
| 612 |
see `Order of MIDDLEWARE`_ below if you'd like the full story. |
| 613 |
|
| 614 |
Then, add the following required settings to your Django settings file: |
| 615 |
|
| 616 |
* :setting:`CACHE_MIDDLEWARE_ALIAS` -- The cache alias to use for storage. |
| 617 |
* :setting:`CACHE_MIDDLEWARE_SECONDS` -- The integer number of seconds each |
| 618 |
page should be cached. |
| 619 |
|
| 620 |
* :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` -- If the cache is shared across |
| 621 |
multiple sites using the same Django installation, set this to the name of |
| 622 |
the site, or some other string that is unique to this Django instance, to |
| 623 |
prevent key collisions. Use an empty string if you don't care. |
| 624 |
|
| 625 |
``FetchFromCacheMiddleware`` caches GET and HEAD responses with status 200, |
| 626 |
where the request and response headers allow. Responses to requests for the same |
| 627 |
URL with different query parameters are considered to be unique pages and are |
| 628 |
cached separately. This middleware expects that a HEAD request is answered with |
| 629 |
the same response headers as the corresponding GET request; in which case it can |
| 630 |
return a cached GET response for HEAD request. |
| 631 |
|
| 632 |
Additionally, ``UpdateCacheMiddleware`` automatically sets a few headers in |
| 633 |
each :class:`~django.http.HttpResponse` which affect :ref:`downstream caches |
| 634 |
<downstream-caches>`: |
| 635 |
|
| 636 |
* Sets the ``Expires`` header to the current date/time plus the defined |
| 637 |
:setting:`CACHE_MIDDLEWARE_SECONDS`. |
| 638 |
|
| 639 |
* Sets the ``Cache-Control`` header to give a max age for the page -- |
| 640 |
again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. |
| 641 |
|
| 642 |
See :doc:`/topics/http/middleware` for more on middleware. |
| 643 |
|
| 644 |
If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in |
| 645 |
its ``Cache-Control`` header) then the page will be cached until the expiry |
| 646 |
time, rather than :setting:`CACHE_MIDDLEWARE_SECONDS`. Using the decorators in |
| 647 |
``django.views.decorators.cache`` you can easily set a view's expiry time |
| 648 |
(using the :func:`~django.views.decorators.cache.cache_control` decorator) or |
| 649 |
disable caching for a view (using the |
| 650 |
:func:`~django.views.decorators.cache.never_cache` decorator). See the |
| 651 |
`using other headers`__ section for more on these decorators. |
| 652 |
|
| 653 |
.. _i18n-cache-key: |
| 654 |
|
| 655 |
If :setting:`USE_I18N` is set to ``True`` then the generated cache key will |
| 656 |
include the name of the active :term:`language<language code>` -- see also |
| 657 |
:ref:`how-django-discovers-language-preference`). This allows you to easily |
| 658 |
cache multilingual sites without having to create the cache key yourself. |
| 659 |
|
| 660 |
Cache keys also include the :ref:`current time zone |
| 661 |
<default-current-time-zone>` when :setting:`USE_TZ` is set to ``True``. |
| 662 |
|
| 663 |
__ `Controlling cache: Using other headers`_ |
| 664 |
|
| 665 |
The per-view cache |
| 666 |
================== |
| 667 |
|
| 668 |
.. function:: django.views.decorators.cache.cache_page(timeout, *, cache=None, key_prefix=None) |
| 669 |
|
| 670 |
A more granular way to use the caching framework is by caching the output of |
| 671 |
individual views. ``django.views.decorators.cache`` defines a ``cache_page`` |
| 672 |
decorator that will automatically cache the view's response for you:: |
| 673 |
|
| 674 |
from django.views.decorators.cache import cache_page |
| 675 |
|
| 676 |
|
| 677 |
@cache_page(60 * 15) |
| 678 |
def my_view(request): ... |
| 679 |
|
| 680 |
``cache_page`` takes a single argument: the cache timeout, in seconds. In the |
| 681 |
above example, the result of the ``my_view()`` view will be cached for 15 |
| 682 |
minutes. (Note that we've written it as ``60 * 15`` for the purpose of |
| 683 |
readability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes |
| 684 |
multiplied by 60 seconds per minute.) |
| 685 |
|
| 686 |
The cache timeout set by ``cache_page`` takes precedence over the ``max-age`` |
| 687 |
directive from the ``Cache-Control`` header. |
| 688 |
|
| 689 |
The per-view cache, like the per-site cache, is keyed off of the URL. If |
| 690 |
multiple URLs point at the same view, each URL will be cached separately. |
| 691 |
Continuing the ``my_view`` example, if your URLconf looks like this:: |
| 692 |
|
| 693 |
urlpatterns = [ |
| 694 |
path("foo/<int:code>/", my_view), |
| 695 |
] |
| 696 |
|
| 697 |
then requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as |
| 698 |
you may expect. But once a particular URL (e.g., ``/foo/23/``) has been |
| 699 |
requested, subsequent requests to that URL will use the cache. |
| 700 |
|
| 701 |
``cache_page`` can also take an optional keyword argument, ``cache``, |
| 702 |
which directs the decorator to use a specific cache (from your |
| 703 |
:setting:`CACHES` setting) when caching view results. By default, the |
| 704 |
``default`` cache will be used, but you can specify any cache you |
| 705 |
want:: |
| 706 |
|
| 707 |
@cache_page(60 * 15, cache="special_cache") |
| 708 |
def my_view(request): ... |
| 709 |
|
| 710 |
You can also override the cache prefix on a per-view basis. ``cache_page`` |
| 711 |
takes an optional keyword argument, ``key_prefix``, |
| 712 |
which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` |
| 713 |
setting for the middleware. It can be used like this:: |
| 714 |
|
| 715 |
@cache_page(60 * 15, key_prefix="site1") |
| 716 |
def my_view(request): ... |
| 717 |
|
| 718 |
The ``key_prefix`` and ``cache`` arguments may be specified together. The |
| 719 |
``key_prefix`` argument and the :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` |
| 720 |
specified under :setting:`CACHES` will be concatenated. |
| 721 |
|
| 722 |
Additionally, ``cache_page`` automatically sets ``Cache-Control`` and |
| 723 |
``Expires`` headers in the response which affect :ref:`downstream caches |
| 724 |
<downstream-caches>`. |
| 725 |
|
| 726 |
Specifying per-view cache in the URLconf |
| 727 |
---------------------------------------- |
| 728 |
|
| 729 |
The examples in the previous section have hard-coded the fact that the view is |
| 730 |
cached, because ``cache_page`` alters the ``my_view`` function in place. This |
| 731 |
approach couples your view to the cache system, which is not ideal for several |
| 732 |
reasons. For instance, you might want to reuse the view functions on another, |
| 733 |
cache-less site, or you might want to distribute the views to people who might |
| 734 |
want to use them without being cached. The solution to these problems is to |
| 735 |
specify the per-view cache in the URLconf rather than next to the view functions |
| 736 |
themselves. |
| 737 |
|
| 738 |
You can do so by wrapping the view function with ``cache_page`` when you refer |
| 739 |
to it in the URLconf. Here's the old URLconf from earlier:: |
| 740 |
|
| 741 |
urlpatterns = [ |
| 742 |
path("foo/<int:code>/", my_view), |
| 743 |
] |
| 744 |
|
| 745 |
Here's the same thing, with ``my_view`` wrapped in ``cache_page``:: |
| 746 |
|
| 747 |
from django.views.decorators.cache import cache_page |
| 748 |
|
| 749 |
urlpatterns = [ |
| 750 |
path("foo/<int:code>/", cache_page(60 * 15)(my_view)), |
| 751 |
] |
| 752 |
|
| 753 |
.. templatetag:: cache |
| 754 |
|
| 755 |
Template fragment caching |
| 756 |
========================= |
| 757 |
|
| 758 |
If you're after even more control, you can also cache template fragments using |
| 759 |
the ``cache`` template tag. To give your template access to this tag, put |
| 760 |
``{% load cache %}`` near the top of your template. |
| 761 |
|
| 762 |
The ``{% cache %}`` template tag caches the contents of the block for a given |
| 763 |
amount of time. It takes at least two arguments: the cache timeout, in seconds, |
| 764 |
and the name to give the cache fragment. The fragment is cached forever if |
| 765 |
timeout is ``None``. The name will be taken as is, do not use a variable. For |
| 766 |
example: |
| 767 |
|
| 768 |
.. code-block:: html+django |
| 769 |
|
| 770 |
{% load cache %} |
| 771 |
{% cache 500 sidebar %} |
| 772 |
.. sidebar .. |
| 773 |
{% endcache %} |
| 774 |
|
| 775 |
Sometimes you might want to cache multiple copies of a fragment depending on |
| 776 |
some dynamic data that appears inside the fragment. For example, you might want a |
| 777 |
separate cached copy of the sidebar used in the previous example for every user |
| 778 |
of your site. Do this by passing one or more additional arguments, which may be |
| 779 |
variables with or without filters, to the ``{% cache %}`` template tag to |
| 780 |
uniquely identify the cache fragment: |
| 781 |
|
| 782 |
.. code-block:: html+django |
| 783 |
|
| 784 |
{% load cache %} |
| 785 |
{% cache 500 sidebar request.user.username %} |
| 786 |
.. sidebar for logged-in user .. |
| 787 |
{% endcache %} |
| 788 |
|
| 789 |
If :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will |
| 790 |
:ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template |
| 791 |
tag you could use one of the |
| 792 |
:ref:`translation-specific variables<template-translation-vars>` available in |
| 793 |
templates to achieve the same result: |
| 794 |
|
| 795 |
.. code-block:: html+django |
| 796 |
|
| 797 |
{% load i18n %} |
| 798 |
{% load cache %} |
| 799 |
|
| 800 |
{% get_current_language as LANGUAGE_CODE %} |
| 801 |
|
| 802 |
{% cache 600 welcome LANGUAGE_CODE %} |
| 803 |
{% translate "Welcome to example.com" %} |
| 804 |
{% endcache %} |
| 805 |
|
| 806 |
The cache timeout can be a template variable, as long as the template variable |
| 807 |
resolves to an integer value. For example, if the template variable |
| 808 |
``my_timeout`` is set to the value ``600``, then the following two examples are |
| 809 |
equivalent: |
| 810 |
|
| 811 |
.. code-block:: html+django |
| 812 |
|
| 813 |
{% cache 600 sidebar %} ... {% endcache %} |
| 814 |
{% cache my_timeout sidebar %} ... {% endcache %} |
| 815 |
|
| 816 |
This feature is useful in avoiding repetition in templates. You can set the |
| 817 |
timeout in a variable, in one place, and reuse that value. |
| 818 |
|
| 819 |
By default, the cache tag will try to use the cache called "template_fragments". |
| 820 |
If no such cache exists, it will fall back to using the default cache. You may |
| 821 |
select an alternate cache backend to use with the ``using`` keyword argument, |
| 822 |
which must be the last argument to the tag. |
| 823 |
|
| 824 |
.. code-block:: html+django |
| 825 |
|
| 826 |
{% cache 300 local-thing ... using="localcache" %} |
| 827 |
|
| 828 |
It is considered an error to specify a cache name that is not configured. |
| 829 |
|
| 830 |
.. function:: django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None) |
| 831 |
|
| 832 |
If you want to obtain the cache key used for a cached fragment, you can use |
| 833 |
``make_template_fragment_key``. ``fragment_name`` is the same as second argument |
| 834 |
to the ``cache`` template tag; ``vary_on`` is a list of all additional arguments |
| 835 |
passed to the tag. This function can be useful for invalidating or overwriting |
| 836 |
a cached item, for example: |
| 837 |
|
| 838 |
.. code-block:: pycon |
| 839 |
|
| 840 |
>>> from django.core.cache import cache |
| 841 |
>>> from django.core.cache.utils import make_template_fragment_key |
| 842 |
# cache key for {% cache 500 sidebar username %} |
| 843 |
>>> key = make_template_fragment_key("sidebar", [username]) |
| 844 |
>>> cache.delete(key) # invalidates cached template fragment |
| 845 |
True |
| 846 |
|
| 847 |
.. _low-level-cache-api: |
| 848 |
|
| 849 |
The low-level cache API |
| 850 |
======================= |
| 851 |
|
| 852 |
Sometimes, caching an entire rendered page doesn't gain you very much and is, |
| 853 |
in fact, inconvenient overkill. |
| 854 |
|
| 855 |
Perhaps, for instance, your site includes a view whose results depend on |
| 856 |
several expensive queries, the results of which change at different intervals. |
| 857 |
In this case, it would not be ideal to use the full-page caching that the |
| 858 |
per-site or per-view cache strategies offer, because you wouldn't want to |
| 859 |
cache the entire result (since some of the data changes often), but you'd still |
| 860 |
want to cache the results that rarely change. |
| 861 |
|
| 862 |
For cases like this, Django exposes a low-level cache API. You can use this API |
| 863 |
to store objects in the cache with any level of granularity you like. You can |
| 864 |
cache any Python object that can be pickled safely: strings, dictionaries, |
| 865 |
lists of model objects, and so forth. (Most common Python objects can be |
| 866 |
pickled; refer to the :mod:`Python documentation <pickle>` for more information |
| 867 |
about pickling.) |
| 868 |
|
| 869 |
Accessing the cache |
| 870 |
------------------- |
| 871 |
|
| 872 |
.. data:: django.core.cache.caches |
| 873 |
|
| 874 |
You can access the caches configured in the :setting:`CACHES` setting |
| 875 |
through a dict-like object: ``django.core.cache.caches``. Repeated |
| 876 |
requests for the same alias in the same thread will return the same |
| 877 |
object. |
| 878 |
|
| 879 |
.. code-block:: pycon |
| 880 |
|
| 881 |
>>> from django.core.cache import caches |
| 882 |
>>> cache1 = caches["myalias"] |
| 883 |
>>> cache2 = caches["myalias"] |
| 884 |
>>> cache1 is cache2 |
| 885 |
True |
| 886 |
|
| 887 |
If the named key does not exist, ``InvalidCacheBackendError`` will be |
| 888 |
raised. |
| 889 |
|
| 890 |
To provide thread-safety, a different instance of the cache backend will |
| 891 |
be returned for each thread. |
| 892 |
|
| 893 |
.. data:: django.core.cache.cache |
| 894 |
|
| 895 |
As a shortcut, the default cache is available as |
| 896 |
``django.core.cache.cache``: |
| 897 |
|
| 898 |
.. code-block:: pycon |
| 899 |
|
| 900 |
>>> from django.core.cache import cache |
| 901 |
|
| 902 |
This object is equivalent to ``caches['default']``. |
| 903 |
|
| 904 |
.. _cache-basic-interface: |
| 905 |
|
| 906 |
Basic usage |
| 907 |
----------- |
| 908 |
|
| 909 |
.. currentmodule:: django.core.cache |
| 910 |
|
| 911 |
The basic interface is: |
| 912 |
|
| 913 |
.. method:: cache.set(key, value, timeout=DEFAULT_TIMEOUT, version=None) |
| 914 |
|
| 915 |
.. code-block:: pycon |
| 916 |
|
| 917 |
>>> cache.set("my_key", "hello, world!", 30) |
| 918 |
|
| 919 |
.. method:: cache.get(key, default=None, version=None) |
| 920 |
|
| 921 |
.. code-block:: pycon |
| 922 |
|
| 923 |
>>> cache.get("my_key") |
| 924 |
'hello, world!' |
| 925 |
|
| 926 |
``key`` should be a ``str``, and ``value`` can be any picklable Python object. |
| 927 |
|
| 928 |
The ``timeout`` argument is optional and defaults to the ``timeout`` argument |
| 929 |
of the appropriate backend in the :setting:`CACHES` setting (explained above). |
| 930 |
It's the number of seconds the value should be stored in the cache. Passing in |
| 931 |
``None`` for ``timeout`` will cache the value forever. A ``timeout`` of ``0`` |
| 932 |
won't cache the value. |
| 933 |
|
| 934 |
If the object doesn't exist in the cache, ``cache.get()`` returns ``None``: |
| 935 |
|
| 936 |
.. code-block:: pycon |
| 937 |
|
| 938 |
>>> # Wait 30 seconds for 'my_key' to expire... |
| 939 |
>>> cache.get("my_key") |
| 940 |
None |
| 941 |
|
| 942 |
If you need to determine whether the object exists in the cache and you have |
| 943 |
stored a literal value ``None``, use a sentinel object as the default: |
| 944 |
|
| 945 |
.. code-block:: pycon |
| 946 |
|
| 947 |
>>> sentinel = object() |
| 948 |
>>> cache.get("my_key", sentinel) is sentinel |
| 949 |
False |
| 950 |
>>> # Wait 30 seconds for 'my_key' to expire... |
| 951 |
>>> cache.get("my_key", sentinel) is sentinel |
| 952 |
True |
| 953 |
|
| 954 |
``cache.get()`` can take a ``default`` argument. This specifies which value to |
| 955 |
return if the object doesn't exist in the cache: |
| 956 |
|
| 957 |
.. code-block:: pycon |
| 958 |
|
| 959 |
>>> cache.get("my_key", "has expired") |
| 960 |
'has expired' |
| 961 |
|
| 962 |
.. method:: cache.add(key, value, timeout=DEFAULT_TIMEOUT, version=None) |
| 963 |
|
| 964 |
To add a key only if it doesn't already exist, use the ``add()`` method. |
| 965 |
It takes the same parameters as ``set()``, but it will not attempt to |
| 966 |
update the cache if the key specified is already present: |
| 967 |
|
| 968 |
.. code-block:: pycon |
| 969 |
|
| 970 |
>>> cache.set("add_key", "Initial value") |
| 971 |
>>> cache.add("add_key", "New value") |
| 972 |
>>> cache.get("add_key") |
| 973 |
'Initial value' |
| 974 |
|
| 975 |
If you need to know whether ``add()`` stored a value in the cache, you can |
| 976 |
check the return value. It will return ``True`` if the value was stored, |
| 977 |
``False`` otherwise. |
| 978 |
|
| 979 |
.. method:: cache.get_or_set(key, default, timeout=DEFAULT_TIMEOUT, version=None) |
| 980 |
|
| 981 |
If you want to get a key's value or set a value if the key isn't in the cache, |
| 982 |
there is the ``get_or_set()`` method. It takes the same parameters as ``get()`` |
| 983 |
but the default is set as the new cache value for that key, rather than |
| 984 |
returned: |
| 985 |
|
| 986 |
.. code-block:: pycon |
| 987 |
|
| 988 |
>>> cache.get("my_new_key") # returns None |
| 989 |
>>> cache.get_or_set("my_new_key", "my new value", 100) |
| 990 |
'my new value' |
| 991 |
|
| 992 |
You can also pass any callable as a *default* value: |
| 993 |
|
| 994 |
.. code-block:: pycon |
| 995 |
|
| 996 |
>>> import datetime |
| 997 |
>>> cache.get_or_set("some-timestamp-key", datetime.datetime.now) |
| 998 |
datetime.datetime(2014, 12, 11, 0, 15, 49, 457920) |
| 999 |
|
| 1000 |
.. method:: cache.get_many(keys, version=None) |
| 1001 |
|
| 1002 |
There's also a ``get_many()`` interface that only hits the cache once. |
| 1003 |
``get_many()`` returns a dictionary with all the keys you asked for that |
| 1004 |
actually exist in the cache (and haven't expired): |
| 1005 |
|
| 1006 |
.. code-block:: pycon |
| 1007 |
|
| 1008 |
>>> cache.set("a", 1) |
| 1009 |
>>> cache.set("b", 2) |
| 1010 |
>>> cache.set("c", 3) |
| 1011 |
>>> cache.get_many(["a", "b", "c"]) |
| 1012 |
{'a': 1, 'b': 2, 'c': 3} |
| 1013 |
|
| 1014 |
.. method:: cache.set_many(dict, timeout) |
| 1015 |
|
| 1016 |
To set multiple values more efficiently, use ``set_many()`` to pass a dictionary |
| 1017 |
of key-value pairs: |
| 1018 |
|
| 1019 |
.. code-block:: pycon |
| 1020 |
|
| 1021 |
>>> cache.set_many({"a": 1, "b": 2, "c": 3}) |
| 1022 |
>>> cache.get_many(["a", "b", "c"]) |
| 1023 |
{'a': 1, 'b': 2, 'c': 3} |
| 1024 |
|
| 1025 |
Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter. |
| 1026 |
|
| 1027 |
On supported backends (memcached), ``set_many()`` returns a list of keys that |
| 1028 |
failed to be inserted. |
| 1029 |
|
| 1030 |
.. method:: cache.delete(key, version=None) |
| 1031 |
|
| 1032 |
You can delete keys explicitly with ``delete()`` to clear the cache for a |
| 1033 |
particular object: |
| 1034 |
|
| 1035 |
.. code-block:: pycon |
| 1036 |
|
| 1037 |
>>> cache.delete("a") |
| 1038 |
True |
| 1039 |
|
| 1040 |
``delete()`` returns ``True`` if the key was successfully deleted, ``False`` |
| 1041 |
otherwise. |
| 1042 |
|
| 1043 |
.. method:: cache.delete_many(keys, version=None) |
| 1044 |
|
| 1045 |
If you want to clear a bunch of keys at once, ``delete_many()`` can take a list |
| 1046 |
of keys to be cleared: |
| 1047 |
|
| 1048 |
.. code-block:: pycon |
| 1049 |
|
| 1050 |
>>> cache.delete_many(["a", "b", "c"]) |
| 1051 |
|
| 1052 |
.. method:: cache.clear() |
| 1053 |
|
| 1054 |
Finally, if you want to delete all the keys in the cache, use |
| 1055 |
``cache.clear()``. Be careful with this; ``clear()`` will remove *everything* |
| 1056 |
from the cache, not just the keys set by your application: |
| 1057 |
|
| 1058 |
.. code-block:: pycon |
| 1059 |
|
| 1060 |
>>> cache.clear() |
| 1061 |
|
| 1062 |
.. method:: cache.touch(key, timeout=DEFAULT_TIMEOUT, version=None) |
| 1063 |
|
| 1064 |
``cache.touch()`` sets a new expiration for a key. For example, to update a key |
| 1065 |
to expire 10 seconds from now: |
| 1066 |
|
| 1067 |
.. code-block:: pycon |
| 1068 |
|
| 1069 |
>>> cache.touch("a", 10) |
| 1070 |
True |
| 1071 |
|
| 1072 |
Like other methods, the ``timeout`` argument is optional and defaults to the |
| 1073 |
``TIMEOUT`` option of the appropriate backend in the :setting:`CACHES` setting. |
| 1074 |
|
| 1075 |
``touch()`` returns ``True`` if the key was successfully touched, ``False`` |
| 1076 |
otherwise. |
| 1077 |
|
| 1078 |
.. method:: cache.incr(key, delta=1, version=None) |
| 1079 |
.. method:: cache.decr(key, delta=1, version=None) |
| 1080 |
|
| 1081 |
You can also increment or decrement a key that already exists using the |
| 1082 |
``incr()`` or ``decr()`` methods, respectively. By default, the existing cache |
| 1083 |
value will be incremented or decremented by 1. Other increment/decrement values |
| 1084 |
can be specified by providing an argument to the increment/decrement call. A |
| 1085 |
ValueError will be raised if you attempt to increment or decrement a |
| 1086 |
nonexistent cache key: |
| 1087 |
|
| 1088 |
.. code-block:: pycon |
| 1089 |
|
| 1090 |
>>> cache.set("num", 1) |
| 1091 |
>>> cache.incr("num") |
| 1092 |
2 |
| 1093 |
>>> cache.incr("num", 10) |
| 1094 |
12 |
| 1095 |
>>> cache.decr("num") |
| 1096 |
11 |
| 1097 |
>>> cache.decr("num", 5) |
| 1098 |
6 |
| 1099 |
|
| 1100 |
.. note:: |
| 1101 |
|
| 1102 |
``incr()``/``decr()`` methods are not guaranteed to be atomic. On those |
| 1103 |
backends that support atomic increment/decrement (most notably, the |
| 1104 |
memcached backend), increment and decrement operations will be atomic. |
| 1105 |
However, if the backend doesn't natively provide an increment/decrement |
| 1106 |
operation, it will be implemented using a two-step retrieve/update. |
| 1107 |
|
| 1108 |
.. method:: cache.close() |
| 1109 |
|
| 1110 |
You can close the connection to your cache with ``close()`` if implemented by |
| 1111 |
the cache backend. |
| 1112 |
|
| 1113 |
.. code-block:: pycon |
| 1114 |
|
| 1115 |
>>> cache.close() |
| 1116 |
|
| 1117 |
.. note:: |
| 1118 |
|
| 1119 |
For caches that don't implement ``close`` methods it is a no-op. |
| 1120 |
|
| 1121 |
.. note:: |
| 1122 |
|
| 1123 |
The async variants of base methods are prefixed with ``a``, e.g. |
| 1124 |
``cache.aadd()`` or ``cache.adelete_many()``. See `Asynchronous support`_ |
| 1125 |
for more details. |
| 1126 |
|
| 1127 |
.. _cache_key_prefixing: |
| 1128 |
|
| 1129 |
Cache key prefixing |
| 1130 |
------------------- |
| 1131 |
|
| 1132 |
If you are sharing a cache instance between servers, or between your |
| 1133 |
production and development environments, it's possible for data cached |
| 1134 |
by one server to be used by another server. If the format of cached |
| 1135 |
data is different between servers, this can lead to some very hard to |
| 1136 |
diagnose problems. |
| 1137 |
|
| 1138 |
To prevent this, Django provides the ability to prefix all cache keys |
| 1139 |
used by a server. When a particular cache key is saved or retrieved, |
| 1140 |
Django will automatically prefix the cache key with the value of the |
| 1141 |
:setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` cache setting. |
| 1142 |
|
| 1143 |
By ensuring each Django instance has a different |
| 1144 |
:setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`, you can ensure that there will be no |
| 1145 |
collisions in cache values. |
| 1146 |
|
| 1147 |
.. _cache_versioning: |
| 1148 |
|
| 1149 |
Cache versioning |
| 1150 |
---------------- |
| 1151 |
|
| 1152 |
When you change running code that uses cached values, you may need to |
| 1153 |
purge any existing cached values. The easiest way to do this is to |
| 1154 |
flush the entire cache, but this can lead to the loss of cache values |
| 1155 |
that are still valid and useful. |
| 1156 |
|
| 1157 |
Django provides a better way to target individual cache values. |
| 1158 |
Django's cache framework has a system-wide version identifier, |
| 1159 |
specified using the :setting:`VERSION <CACHES-VERSION>` cache setting. |
| 1160 |
The value of this setting is automatically combined with the cache |
| 1161 |
prefix and the user-provided cache key to obtain the final cache key. |
| 1162 |
|
| 1163 |
By default, any key request will automatically include the site |
| 1164 |
default cache key version. However, the primitive cache functions all |
| 1165 |
include a ``version`` argument, so you can specify a particular cache |
| 1166 |
key version to set or get. For example: |
| 1167 |
|
| 1168 |
.. code-block:: pycon |
| 1169 |
|
| 1170 |
>>> # Set version 2 of a cache key |
| 1171 |
>>> cache.set("my_key", "hello world!", version=2) |
| 1172 |
>>> # Get the default version (assuming version=1) |
| 1173 |
>>> cache.get("my_key") |
| 1174 |
None |
| 1175 |
>>> # Get version 2 of the same key |
| 1176 |
>>> cache.get("my_key", version=2) |
| 1177 |
'hello world!' |
| 1178 |
|
| 1179 |
The version of a specific key can be incremented and decremented using |
| 1180 |
the ``incr_version()`` and ``decr_version()`` methods. This |
| 1181 |
enables specific keys to be bumped to a new version, leaving other |
| 1182 |
keys unaffected. Continuing our previous example: |
| 1183 |
|
| 1184 |
.. code-block:: pycon |
| 1185 |
|
| 1186 |
>>> # Increment the version of 'my_key' |
| 1187 |
>>> cache.incr_version("my_key") |
| 1188 |
>>> # The default version still isn't available |
| 1189 |
>>> cache.get("my_key") |
| 1190 |
None |
| 1191 |
# Version 2 isn't available, either |
| 1192 |
>>> cache.get("my_key", version=2) |
| 1193 |
None |
| 1194 |
>>> # But version 3 *is* available |
| 1195 |
>>> cache.get("my_key", version=3) |
| 1196 |
'hello world!' |
| 1197 |
|
| 1198 |
.. _cache_key_transformation: |
| 1199 |
|
| 1200 |
Cache key transformation |
| 1201 |
------------------------ |
| 1202 |
|
| 1203 |
As described in the previous two sections, the cache key provided by a |
| 1204 |
user is not used verbatim -- it is combined with the cache prefix and |
| 1205 |
key version to provide a final cache key. By default, the three parts |
| 1206 |
are joined using colons to produce a final string:: |
| 1207 |
|
| 1208 |
def make_key(key, key_prefix, version): |
| 1209 |
return "%s:%s:%s" % (key_prefix, version, key) |
| 1210 |
|
| 1211 |
If you want to combine the parts in different ways, or apply other |
| 1212 |
processing to the final key (e.g., taking a hash digest of the key |
| 1213 |
parts), you can provide a custom key function. |
| 1214 |
|
| 1215 |
The :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting |
| 1216 |
specifies a dotted-path to a function matching the prototype of |
| 1217 |
``make_key()`` above. If provided, this custom key function will |
| 1218 |
be used instead of the default key combining function. |
| 1219 |
|
| 1220 |
Cache key warnings |
| 1221 |
------------------ |
| 1222 |
|
| 1223 |
Memcached, the most commonly-used production cache backend, does not allow |
| 1224 |
cache keys longer than 250 characters or containing whitespace or control |
| 1225 |
characters, and using such keys will cause an exception. To encourage |
| 1226 |
cache-portable code and minimize unpleasant surprises, the other built-in cache |
| 1227 |
backends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``) |
| 1228 |
if a key is used that would cause an error on memcached. |
| 1229 |
|
| 1230 |
If you are using a production backend that can accept a wider range of keys (a |
| 1231 |
custom backend, or one of the non-memcached built-in backends), and want to use |
| 1232 |
this wider range without warnings, you can silence ``CacheKeyWarning`` with |
| 1233 |
this code in the ``management`` module of one of your |
| 1234 |
:setting:`INSTALLED_APPS`:: |
| 1235 |
|
| 1236 |
import warnings |
| 1237 |
|
| 1238 |
from django.core.cache import CacheKeyWarning |
| 1239 |
|
| 1240 |
warnings.simplefilter("ignore", CacheKeyWarning) |
| 1241 |
|
| 1242 |
If you want to instead provide custom key validation logic for one of the |
| 1243 |
built-in backends, you can subclass it, override just the ``validate_key`` |
| 1244 |
method, and follow the instructions for `using a custom cache backend`_. For |
| 1245 |
instance, to do this for the ``locmem`` backend, put this code in a module:: |
| 1246 |
|
| 1247 |
from django.core.cache.backends.locmem import LocMemCache |
| 1248 |
|
| 1249 |
|
| 1250 |
class CustomLocMemCache(LocMemCache): |
| 1251 |
def validate_key(self, key): |
| 1252 |
"""Custom validation, raising exceptions or warnings as needed.""" |
| 1253 |
... |
| 1254 |
|
| 1255 |
...and use the dotted Python path to this class in the |
| 1256 |
:setting:`BACKEND <CACHES-BACKEND>` portion of your :setting:`CACHES` setting. |
| 1257 |
|
| 1258 |
.. _asynchronous_support: |
| 1259 |
|
| 1260 |
Asynchronous support |
| 1261 |
==================== |
| 1262 |
|
| 1263 |
Django has developing support for asynchronous cache backends, but does not |
| 1264 |
yet support asynchronous caching. It will be coming in a future release. |
| 1265 |
|
| 1266 |
``django.core.cache.backends.base.BaseCache`` has async variants of :ref:`all |
| 1267 |
base methods <cache-basic-interface>`. By convention, the asynchronous versions |
| 1268 |
of all methods are prefixed with ``a``. By default, the arguments for both |
| 1269 |
variants are the same: |
| 1270 |
|
| 1271 |
.. code-block:: pycon |
| 1272 |
|
| 1273 |
>>> await cache.aset("num", 1) |
| 1274 |
>>> await cache.ahas_key("num") |
| 1275 |
True |
| 1276 |
|
| 1277 |
.. _downstream-caches: |
| 1278 |
|
| 1279 |
Downstream caches |
| 1280 |
================= |
| 1281 |
|
| 1282 |
So far, this document has focused on caching your *own* data. But another type |
| 1283 |
of caching is relevant to web development, too: caching performed by |
| 1284 |
"downstream" caches. These are systems that cache pages for users even before |
| 1285 |
the request reaches your website. |
| 1286 |
|
| 1287 |
Here are a few examples of downstream caches: |
| 1288 |
|
| 1289 |
* When using HTTP, your :abbr:`ISP (Internet Service Provider)` may cache |
| 1290 |
certain pages, so if you requested a page from ``http://example.com/``, your |
| 1291 |
ISP would send you the page without having to access example.com directly. |
| 1292 |
The maintainers of example.com have no knowledge of this caching; the ISP |
| 1293 |
sits between example.com and your web browser, handling all of the caching |
| 1294 |
transparently. Such caching is not possible under HTTPS as it would |
| 1295 |
constitute a man-in-the-middle attack. |
| 1296 |
|
| 1297 |
* Your Django website may sit behind a *proxy cache*, such as Squid Web |
| 1298 |
Proxy Cache (http://www.squid-cache.org/), that caches pages for |
| 1299 |
performance. In this case, each request first would be handled by the |
| 1300 |
proxy, and it would be passed to your application only if needed. |
| 1301 |
|
| 1302 |
* Your web browser caches pages, too. If a web page sends out the |
| 1303 |
appropriate headers, your browser will use the local cached copy for |
| 1304 |
subsequent requests to that page, without even contacting the web page |
| 1305 |
again to see whether it has changed. |
| 1306 |
|
| 1307 |
Downstream caching is a nice efficiency boost, but there's a danger to it: |
| 1308 |
Many web pages' contents differ based on authentication and a host of other |
| 1309 |
variables, and cache systems that blindly save pages based purely on URLs could |
| 1310 |
expose incorrect or sensitive data to subsequent visitors to those pages. |
| 1311 |
|
| 1312 |
For example, if you operate a web email system, then the contents of the |
| 1313 |
"inbox" page depend on which user is logged in. If an ISP blindly cached your |
| 1314 |
site, then the first user who logged in through that ISP would have their |
| 1315 |
user-specific inbox page cached for subsequent visitors to the site. That's |
| 1316 |
not cool. |
| 1317 |
|
| 1318 |
Fortunately, HTTP provides a solution to this problem. A number of HTTP headers |
| 1319 |
exist to instruct downstream caches to differ their cache contents depending on |
| 1320 |
designated variables, and to tell caching mechanisms not to cache particular |
| 1321 |
pages. We'll look at some of these headers in the sections that follow. |
| 1322 |
|
| 1323 |
.. _using-vary-headers: |
| 1324 |
|
| 1325 |
Using ``Vary`` headers |
| 1326 |
====================== |
| 1327 |
|
| 1328 |
The ``Vary`` header defines which request headers a cache |
| 1329 |
mechanism should take into account when building its cache key. For example, if |
| 1330 |
the contents of a web page depend on a user's language preference, the page is |
| 1331 |
said to "vary on language." |
| 1332 |
|
| 1333 |
By default, Django's cache system creates its cache keys using the requested |
| 1334 |
fully-qualified URL -- e.g., |
| 1335 |
``"https://www.example.com/stories/2005/?order_by=author"``. This means every |
| 1336 |
request to that URL will use the same cached version, regardless of user-agent |
| 1337 |
differences such as cookies or language preferences. However, if this page |
| 1338 |
produces different content based on some difference in request headers -- such |
| 1339 |
as a cookie, or a language, or a user-agent -- you'll need to use the ``Vary`` |
| 1340 |
header to tell caching mechanisms that the page output depends on those things. |
| 1341 |
|
| 1342 |
To do this in Django, use the convenient |
| 1343 |
:func:`django.views.decorators.vary.vary_on_headers` view decorator, like so:: |
| 1344 |
|
| 1345 |
from django.views.decorators.vary import vary_on_headers |
| 1346 |
|
| 1347 |
|
| 1348 |
@vary_on_headers("User-Agent") |
| 1349 |
def my_view(request): ... |
| 1350 |
|
| 1351 |
In this case, a caching mechanism (such as Django's own cache middleware) will |
| 1352 |
cache a separate version of the page for each unique user-agent. |
| 1353 |
|
| 1354 |
The advantage to using the ``vary_on_headers`` decorator rather than manually |
| 1355 |
setting the ``Vary`` header (using something like ``response.headers['Vary'] = |
| 1356 |
'user-agent'``) is that the decorator *adds* to the ``Vary`` header (which may |
| 1357 |
already exist), rather than setting it from scratch and potentially overriding |
| 1358 |
anything that was already in there. |
| 1359 |
|
| 1360 |
You can pass multiple headers to ``vary_on_headers()``:: |
| 1361 |
|
| 1362 |
@vary_on_headers("User-Agent", "Cookie") |
| 1363 |
def my_view(request): ... |
| 1364 |
|
| 1365 |
This tells downstream caches to vary on *both*, which means each combination of |
| 1366 |
user-agent and cookie will get its own cache value. For example, a request with |
| 1367 |
the user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered |
| 1368 |
different from a request with the user-agent ``Mozilla`` and the cookie value |
| 1369 |
``foo=ham``. |
| 1370 |
|
| 1371 |
Because varying on cookie is so common, there's a |
| 1372 |
:func:`django.views.decorators.vary.vary_on_cookie` decorator. These two views |
| 1373 |
are equivalent:: |
| 1374 |
|
| 1375 |
@vary_on_cookie |
| 1376 |
def my_view(request): ... |
| 1377 |
|
| 1378 |
|
| 1379 |
@vary_on_headers("Cookie") |
| 1380 |
def my_view(request): ... |
| 1381 |
|
| 1382 |
The headers you pass to ``vary_on_headers`` are not case sensitive; |
| 1383 |
``"User-Agent"`` is the same thing as ``"user-agent"``. |
| 1384 |
|
| 1385 |
You can also use a helper function, :func:`django.utils.cache.patch_vary_headers`, |
| 1386 |
directly. This function sets, or adds to, the ``Vary header``. For example:: |
| 1387 |
|
| 1388 |
from django.shortcuts import render |
| 1389 |
from django.utils.cache import patch_vary_headers |
| 1390 |
|
| 1391 |
|
| 1392 |
def my_view(request): |
| 1393 |
... |
| 1394 |
response = render(request, "template_name", context) |
| 1395 |
patch_vary_headers(response, ["Cookie"]) |
| 1396 |
return response |
| 1397 |
|
| 1398 |
``patch_vary_headers`` takes an :class:`~django.http.HttpResponse` instance as |
| 1399 |
its first argument and a list/tuple of case-insensitive header names as its |
| 1400 |
second argument. |
| 1401 |
|
| 1402 |
For more on Vary headers, see the :rfc:`official Vary spec |
| 1403 |
<9110#section-12.5.5>`. |
| 1404 |
|
| 1405 |
.. admonition:: ``CacheMiddleware`` varies on ``Authorization`` automatically |
| 1406 |
|
| 1407 |
Although varying on ``Authorization`` is not strictly necessary given that |
| 1408 |
:rfc:`9111#section-3.5` allows caches to avoid reusing authenticated |
| 1409 |
responses, Django's ``CacheMiddleware`` adds ``Authorization`` to the |
| 1410 |
``Vary`` header to simplify construction of cache keys. |
| 1411 |
|
| 1412 |
.. versionchanged:: 6.0.6 |
| 1413 |
|
| 1414 |
Previously, ``UpdateCacheMiddleware`` did not vary on ``Authorization`` for |
| 1415 |
requests bearing that header. |
| 1416 |
|
| 1417 |
Controlling cache: Using other headers |
| 1418 |
====================================== |
| 1419 |
|
| 1420 |
Other problems with caching are the privacy of data and the question of where |
| 1421 |
data should be stored in a cascade of caches. |
| 1422 |
|
| 1423 |
A user usually faces two kinds of caches: their own browser cache (a private |
| 1424 |
cache) and their provider's cache (a public cache). A public cache is used by |
| 1425 |
multiple users and controlled by someone else. This poses problems with |
| 1426 |
sensitive data--you don't want, say, your bank account number stored in a |
| 1427 |
public cache. So web applications need a way to tell caches which data is |
| 1428 |
private and which is public. |
| 1429 |
|
| 1430 |
The solution is to indicate a page's cache should be "private." To do this in |
| 1431 |
Django, use the :func:`~django.views.decorators.cache.cache_control` view |
| 1432 |
decorator. Example:: |
| 1433 |
|
| 1434 |
from django.views.decorators.cache import cache_control |
| 1435 |
|
| 1436 |
|
| 1437 |
@cache_control(private=True) |
| 1438 |
def my_view(request): ... |
| 1439 |
|
| 1440 |
This decorator takes care of sending out the appropriate HTTP header behind the |
| 1441 |
scenes. |
| 1442 |
|
| 1443 |
Note that the cache control settings "private" and "public" are mutually |
| 1444 |
exclusive. The decorator ensures that the "public" directive is removed if |
| 1445 |
"private" should be set (and vice versa). An example use of the two directives |
| 1446 |
would be a blog site that offers both private and public entries. Public |
| 1447 |
entries may be cached on any shared cache. The following code uses |
| 1448 |
:func:`~django.utils.cache.patch_cache_control`, the manual way to modify the |
| 1449 |
cache control header (it is internally called by the |
| 1450 |
:func:`~django.views.decorators.cache.cache_control` decorator):: |
| 1451 |
|
| 1452 |
from django.views.decorators.cache import patch_cache_control |
| 1453 |
from django.views.decorators.vary import vary_on_cookie |
| 1454 |
|
| 1455 |
|
| 1456 |
@vary_on_cookie |
| 1457 |
def list_blog_entries_view(request): |
| 1458 |
if request.user.is_anonymous: |
| 1459 |
response = render_only_public_entries() |
| 1460 |
patch_cache_control(response, public=True) |
| 1461 |
else: |
| 1462 |
response = render_private_and_public_entries(request.user) |
| 1463 |
patch_cache_control(response, private=True) |
| 1464 |
|
| 1465 |
return response |
| 1466 |
|
| 1467 |
You can control downstream caches in other ways as well (see :rfc:`9111` for |
| 1468 |
details on HTTP caching). For example, even if you don't use Django's |
| 1469 |
server-side cache framework, you can still tell clients to cache a view for a |
| 1470 |
certain amount of time with the :rfc:`max-age <9111#section-5.2.2.1>` |
| 1471 |
directive:: |
| 1472 |
|
| 1473 |
from django.views.decorators.cache import cache_control |
| 1474 |
|
| 1475 |
|
| 1476 |
@cache_control(max_age=3600) |
| 1477 |
def my_view(request): ... |
| 1478 |
|
| 1479 |
(If you *do* use the caching middleware, it already sets the ``max-age`` with |
| 1480 |
the value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. In that case, |
| 1481 |
the custom ``max_age`` from the |
| 1482 |
:func:`~django.views.decorators.cache.cache_control` decorator will take |
| 1483 |
precedence, and the header values will be merged correctly.) |
| 1484 |
|
| 1485 |
Any valid ``Cache-Control`` response directive is valid in ``cache_control()``. |
| 1486 |
Here are some more examples: |
| 1487 |
|
| 1488 |
* ``no_transform=True`` |
| 1489 |
* ``must_revalidate=True`` |
| 1490 |
* ``stale_while_revalidate=num_seconds`` |
| 1491 |
* ``no_cache=True`` |
| 1492 |
|
| 1493 |
The full list of known directives can be found in the `IANA registry`_ |
| 1494 |
(note that not all of them apply to responses). |
| 1495 |
|
| 1496 |
.. _IANA registry: https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml |
| 1497 |
|
| 1498 |
If you want to use headers to disable caching altogether, |
| 1499 |
:func:`~django.views.decorators.cache.never_cache` is a view decorator that |
| 1500 |
adds headers to ensure the response won't be cached by browsers or other |
| 1501 |
caches. Example:: |
| 1502 |
|
| 1503 |
from django.views.decorators.cache import never_cache |
| 1504 |
|
| 1505 |
|
| 1506 |
@never_cache |
| 1507 |
def myview(request): ... |
| 1508 |
|
| 1509 |
Order of ``MIDDLEWARE`` |
| 1510 |
======================= |
| 1511 |
|
| 1512 |
If you use caching middleware, it's important to put each half in the right |
| 1513 |
place within the :setting:`MIDDLEWARE` setting. That's because the cache |
| 1514 |
middleware needs to know which headers by which to vary the cache storage. |
| 1515 |
Middleware always adds something to the ``Vary`` response header when it can. |
| 1516 |
|
| 1517 |
``UpdateCacheMiddleware`` runs during the response phase, where middleware is |
| 1518 |
run in reverse order, so an item at the top of the list runs *last* during the |
| 1519 |
response phase. Thus, you need to make sure that ``UpdateCacheMiddleware`` |
| 1520 |
appears *before* any other middleware that might add something to the ``Vary`` |
| 1521 |
header. The following middleware modules do so: |
| 1522 |
|
| 1523 |
* ``SessionMiddleware`` adds ``Cookie`` |
| 1524 |
* ``GZipMiddleware`` adds ``Accept-Encoding`` |
| 1525 |
* ``LocaleMiddleware`` adds ``Accept-Language`` |
| 1526 |
|
| 1527 |
``FetchFromCacheMiddleware``, on the other hand, runs during the request phase, |
| 1528 |
where middleware is applied first-to-last, so an item at the top of the list |
| 1529 |
runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also |
| 1530 |
needs to run after other middleware updates the ``Vary`` header, so |
| 1531 |
``FetchFromCacheMiddleware`` must be *after* any item that does so. |