cache.txt 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. ========================
  2. Django's cache framework
  3. ========================
  4. A fundamental trade-off in dynamic websites is, well, they're dynamic. Each
  5. time a user requests a page, the Web server makes all sorts of calculations --
  6. from database queries to template rendering to business logic -- to create the
  7. page that your site's visitor sees. This is a lot more expensive, from a
  8. processing-overhead perspective, than your standard
  9. read-a-file-off-the-filesystem server arrangement.
  10. For most Web applications, this overhead isn't a big deal. Most Web
  11. applications aren't ``washingtonpost.com`` or ``slashdot.org``; they're small-
  12. to medium-sized sites with so-so traffic. But for medium- to high-traffic
  13. sites, it's essential to cut as much overhead as possible.
  14. That's where caching comes in.
  15. To cache something is to save the result of an expensive calculation so that
  16. you don't have to perform the calculation next time. Here's some pseudocode
  17. explaining how this would work for a dynamically generated Web page::
  18. given a URL, try finding that page in the cache
  19. if the page is in the cache:
  20. return the cached page
  21. else:
  22. generate the page
  23. save the generated page in the cache (for next time)
  24. return the generated page
  25. Django comes with a robust cache system that lets you save dynamic pages so
  26. they don't have to be calculated for each request. For convenience, Django
  27. offers different levels of cache granularity: You can cache the output of
  28. specific views, you can cache only the pieces that are difficult to produce,
  29. or you can cache your entire site.
  30. Django also works well with "downstream" caches, such as `Squid
  31. <http://www.squid-cache.org>`_ and browser-based caches. These are the types of
  32. caches that you don't directly control but to which you can provide hints (via
  33. HTTP headers) about which parts of your site should be cached, and how.
  34. .. seealso::
  35. The :ref:`Cache Framework design philosophy <cache-design-philosophy>`
  36. explains a few of the design decisions of the framework.
  37. .. _setting-up-the-cache:
  38. Setting up the cache
  39. ====================
  40. The cache system requires a small amount of setup. Namely, you have to tell it
  41. where your cached data should live -- whether in a database, on the filesystem
  42. or directly in memory. This is an important decision that affects your cache's
  43. performance; yes, some cache types are faster than others.
  44. Your cache preference goes in the :setting:`CACHES` setting in your
  45. settings file. Here's an explanation of all available values for
  46. :setting:`CACHES`.
  47. .. _memcached:
  48. Memcached
  49. ---------
  50. The fastest, most efficient type of cache supported natively by Django,
  51. Memcached__ is an entirely memory-based cache server, originally developed
  52. to handle high loads at LiveJournal.com and subsequently open-sourced by
  53. Danga Interactive. It is used by sites such as Facebook and Wikipedia to
  54. reduce database access and dramatically increase site performance.
  55. __ https://memcached.org/
  56. Memcached runs as a daemon and is allotted a specified amount of RAM. All it
  57. does is provide a fast interface for adding, retrieving and deleting data in
  58. the cache. All data is stored directly in memory, so there's no overhead of
  59. database or filesystem usage.
  60. After installing Memcached itself, you'll need to install a Memcached
  61. binding. There are several Python Memcached bindings available; the
  62. two supported by Django are `pylibmc`_ and `pymemcache`_.
  63. .. _`pylibmc`: https://pypi.org/project/pylibmc/
  64. .. _`pymemcache`: https://pypi.org/project/pymemcache/
  65. To use Memcached with Django:
  66. * Set :setting:`BACKEND <CACHES-BACKEND>` to
  67. ``django.core.cache.backends.memcached.PyMemcacheCache`` or
  68. ``django.core.cache.backends.memcached.PyLibMCCache`` (depending on your
  69. chosen memcached binding)
  70. * Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,
  71. where ``ip`` is the IP address of the Memcached daemon and ``port`` is the
  72. port on which Memcached is running, or to a ``unix:path`` value, where
  73. ``path`` is the path to a Memcached Unix socket file.
  74. In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
  75. the ``pymemcache`` binding::
  76. CACHES = {
  77. 'default': {
  78. 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
  79. 'LOCATION': '127.0.0.1:11211',
  80. }
  81. }
  82. In this example, Memcached is available through a local Unix socket file
  83. :file:`/tmp/memcached.sock` using the ``pymemcache`` binding::
  84. CACHES = {
  85. 'default': {
  86. 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
  87. 'LOCATION': 'unix:/tmp/memcached.sock',
  88. }
  89. }
  90. One excellent feature of Memcached is its ability to share a cache over
  91. multiple servers. This means you can run Memcached daemons on multiple
  92. machines, and the program will treat the group of machines as a *single*
  93. cache, without the need to duplicate cache values on each machine. To take
  94. advantage of this feature, include all server addresses in
  95. :setting:`LOCATION <CACHES-LOCATION>`, either as a semicolon or comma
  96. delimited string, or as a list.
  97. In this example, the cache is shared over Memcached instances running on IP
  98. address 172.19.26.240 and 172.19.26.242, both on port 11211::
  99. CACHES = {
  100. 'default': {
  101. 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
  102. 'LOCATION': [
  103. '172.19.26.240:11211',
  104. '172.19.26.242:11211',
  105. ]
  106. }
  107. }
  108. In the following example, the cache is shared over Memcached instances running
  109. on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
  110. 172.19.26.244 (port 11213)::
  111. CACHES = {
  112. 'default': {
  113. 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
  114. 'LOCATION': [
  115. '172.19.26.240:11211',
  116. '172.19.26.242:11212',
  117. '172.19.26.244:11213',
  118. ]
  119. }
  120. }
  121. A final point about Memcached is that memory-based caching has a
  122. disadvantage: because the cached data is stored in memory, the data will be
  123. lost if your server crashes. Clearly, memory isn't intended for permanent data
  124. storage, so don't rely on memory-based caching as your only data storage.
  125. Without a doubt, *none* of the Django caching backends should be used for
  126. permanent storage -- they're all intended to be solutions for caching, not
  127. storage -- but we point this out here because memory-based caching is
  128. particularly temporary.
  129. .. versionchanged:: 3.2
  130. The ``PyMemcacheCache`` backend was added.
  131. .. deprecated:: 3.2
  132. The ``MemcachedCache`` backend is deprecated as ``python-memcached`` has
  133. some problems and seems to be unmaintained. Use ``PyMemcacheCache`` or
  134. ``PyLibMCCache`` instead.
  135. .. _database-caching:
  136. Database caching
  137. ----------------
  138. Django can store its cached data in your database. This works best if you've
  139. got a fast, well-indexed database server.
  140. To use a database table as your cache backend:
  141. * Set :setting:`BACKEND <CACHES-BACKEND>` to
  142. ``django.core.cache.backends.db.DatabaseCache``
  143. * Set :setting:`LOCATION <CACHES-LOCATION>` to ``tablename``, the name of the
  144. database table. This name can be whatever you want, as long as it's a valid
  145. table name that's not already being used in your database.
  146. In this example, the cache table's name is ``my_cache_table``::
  147. CACHES = {
  148. 'default': {
  149. 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
  150. 'LOCATION': 'my_cache_table',
  151. }
  152. }
  153. Creating the cache table
  154. ~~~~~~~~~~~~~~~~~~~~~~~~
  155. Before using the database cache, you must create the cache table with this
  156. command::
  157. python manage.py createcachetable
  158. This creates a table in your database that is in the proper format that
  159. Django's database-cache system expects. The name of the table is taken from
  160. :setting:`LOCATION <CACHES-LOCATION>`.
  161. If you are using multiple database caches, :djadmin:`createcachetable` creates
  162. one table for each cache.
  163. If you are using multiple databases, :djadmin:`createcachetable` observes the
  164. ``allow_migrate()`` method of your database routers (see below).
  165. Like :djadmin:`migrate`, :djadmin:`createcachetable` won't touch an existing
  166. table. It will only create missing tables.
  167. To print the SQL that would be run, rather than run it, use the
  168. :option:`createcachetable --dry-run` option.
  169. Multiple databases
  170. ~~~~~~~~~~~~~~~~~~
  171. If you use database caching with multiple databases, you'll also need
  172. to set up routing instructions for your database cache table. For the
  173. purposes of routing, the database cache table appears as a model named
  174. ``CacheEntry``, in an application named ``django_cache``. This model
  175. won't appear in the models cache, but the model details can be used
  176. for routing purposes.
  177. For example, the following router would direct all cache read
  178. operations to ``cache_replica``, and all write operations to
  179. ``cache_primary``. The cache table will only be synchronized onto
  180. ``cache_primary``::
  181. class CacheRouter:
  182. """A router to control all database cache operations"""
  183. def db_for_read(self, model, **hints):
  184. "All cache read operations go to the replica"
  185. if model._meta.app_label == 'django_cache':
  186. return 'cache_replica'
  187. return None
  188. def db_for_write(self, model, **hints):
  189. "All cache write operations go to primary"
  190. if model._meta.app_label == 'django_cache':
  191. return 'cache_primary'
  192. return None
  193. def allow_migrate(self, db, app_label, model_name=None, **hints):
  194. "Only install the cache model on primary"
  195. if app_label == 'django_cache':
  196. return db == 'cache_primary'
  197. return None
  198. If you don't specify routing directions for the database cache model,
  199. the cache backend will use the ``default`` database.
  200. And if you don't use the database cache backend, you don't need to worry about
  201. providing routing instructions for the database cache model.
  202. Filesystem caching
  203. ------------------
  204. The file-based backend serializes and stores each cache value as a separate
  205. file. To use this backend set :setting:`BACKEND <CACHES-BACKEND>` to
  206. ``"django.core.cache.backends.filebased.FileBasedCache"`` and
  207. :setting:`LOCATION <CACHES-LOCATION>` to a suitable directory. For example,
  208. to store cached data in ``/var/tmp/django_cache``, use this setting::
  209. CACHES = {
  210. 'default': {
  211. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  212. 'LOCATION': '/var/tmp/django_cache',
  213. }
  214. }
  215. If you're on Windows, put the drive letter at the beginning of the path,
  216. like this::
  217. CACHES = {
  218. 'default': {
  219. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  220. 'LOCATION': 'c:/foo/bar',
  221. }
  222. }
  223. The directory path should be absolute -- that is, it should start at the root
  224. of your filesystem. It doesn't matter whether you put a slash at the end of the
  225. setting.
  226. Make sure the directory pointed-to by this setting either exists and is
  227. readable and writable, or that it can be created by the system user under which
  228. your Web server runs. Continuing the above example, if your server runs as the
  229. user ``apache``, make sure the directory ``/var/tmp/django_cache`` exists and
  230. is readable and writable by the user ``apache``, or that it can be created by
  231. the user ``apache``.
  232. .. warning::
  233. When the cache :setting:`LOCATION <CACHES-LOCATION>` is contained within
  234. :setting:`MEDIA_ROOT`, :setting:`STATIC_ROOT`, or
  235. :setting:`STATICFILES_FINDERS`, sensitive data may be exposed.
  236. An attacker who gains access to the cache file can not only falsify HTML
  237. content, which your site will trust, but also remotely execute arbitrary
  238. code, as the data is serialized using :mod:`pickle`.
  239. .. _local-memory-caching:
  240. Local-memory caching
  241. --------------------
  242. This is the default cache if another is not specified in your settings file. If
  243. you want the speed advantages of in-memory caching but don't have the capability
  244. of running Memcached, consider the local-memory cache backend. This cache is
  245. per-process (see below) and thread-safe. To use it, set :setting:`BACKEND
  246. <CACHES-BACKEND>` to ``"django.core.cache.backends.locmem.LocMemCache"``. For
  247. example::
  248. CACHES = {
  249. 'default': {
  250. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  251. 'LOCATION': 'unique-snowflake',
  252. }
  253. }
  254. The cache :setting:`LOCATION <CACHES-LOCATION>` is used to identify individual
  255. memory stores. If you only have one ``locmem`` cache, you can omit the
  256. :setting:`LOCATION <CACHES-LOCATION>`; however, if you have more than one local
  257. memory cache, you will need to assign a name to at least one of them in
  258. order to keep them separate.
  259. The cache uses a least-recently-used (LRU) culling strategy.
  260. Note that each process will have its own private cache instance, which means no
  261. cross-process caching is possible. This also means the local memory cache isn't
  262. particularly memory-efficient, so it's probably not a good choice for
  263. production environments. It's nice for development.
  264. Dummy caching (for development)
  265. -------------------------------
  266. Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
  267. just implements the cache interface without doing anything.
  268. This is useful if you have a production site that uses heavy-duty caching in
  269. various places but a development/test environment where you don't want to cache
  270. and don't want to have to change your code to special-case the latter. To
  271. activate dummy caching, set :setting:`BACKEND <CACHES-BACKEND>` like so::
  272. CACHES = {
  273. 'default': {
  274. 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
  275. }
  276. }
  277. Using a custom cache backend
  278. ----------------------------
  279. While Django includes support for a number of cache backends out-of-the-box,
  280. sometimes you might want to use a customized cache backend. To use an external
  281. cache backend with Django, use the Python import path as the
  282. :setting:`BACKEND <CACHES-BACKEND>` of the :setting:`CACHES` setting, like so::
  283. CACHES = {
  284. 'default': {
  285. 'BACKEND': 'path.to.backend',
  286. }
  287. }
  288. If you're building your own backend, you can use the standard cache backends
  289. as reference implementations. You'll find the code in the
  290. ``django/core/cache/backends/`` directory of the Django source.
  291. Note: Without a really compelling reason, such as a host that doesn't support
  292. them, you should stick to the cache backends included with Django. They've
  293. been well-tested and are well-documented.
  294. .. _cache_arguments:
  295. Cache arguments
  296. ---------------
  297. Each cache backend can be given additional arguments to control caching
  298. behavior. These arguments are provided as additional keys in the
  299. :setting:`CACHES` setting. Valid arguments are as follows:
  300. * :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in
  301. seconds, to use for the cache. This argument defaults to ``300`` seconds (5 minutes).
  302. You can set ``TIMEOUT`` to ``None`` so that, by default, cache keys never
  303. expire. A value of ``0`` causes keys to immediately expire (effectively
  304. "don't cache").
  305. * :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be
  306. passed to the cache backend. The list of valid options will vary
  307. with each backend, and cache backends backed by a third-party library
  308. will pass their options directly to the underlying cache library.
  309. Cache backends that implement their own culling strategy (i.e.,
  310. the ``locmem``, ``filesystem`` and ``database`` backends) will
  311. honor the following options:
  312. * ``MAX_ENTRIES``: The maximum number of entries allowed in
  313. the cache before old values are deleted. This argument
  314. defaults to ``300``.
  315. * ``CULL_FREQUENCY``: The fraction of entries that are culled
  316. when ``MAX_ENTRIES`` is reached. The actual ratio is
  317. ``1 / CULL_FREQUENCY``, so set ``CULL_FREQUENCY`` to ``2`` to
  318. cull half the entries when ``MAX_ENTRIES`` is reached. This argument
  319. should be an integer and defaults to ``3``.
  320. A value of ``0`` for ``CULL_FREQUENCY`` means that the
  321. entire cache will be dumped when ``MAX_ENTRIES`` is reached.
  322. On some backends (``database`` in particular) this makes culling *much*
  323. faster at the expense of more cache misses.
  324. Memcached backends pass the contents of :setting:`OPTIONS <CACHES-OPTIONS>`
  325. as keyword arguments to the client constructors, allowing for more advanced
  326. control of client behavior. For example usage, see below.
  327. * :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be
  328. automatically included (prepended by default) to all cache keys
  329. used by the Django server.
  330. See the :ref:`cache documentation <cache_key_prefixing>` for
  331. more information.
  332. * :setting:`VERSION <CACHES-VERSION>`: The default version number
  333. for cache keys generated by the Django server.
  334. See the :ref:`cache documentation <cache_versioning>` for more
  335. information.
  336. * :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`
  337. A string containing a dotted path to a function that defines how
  338. to compose a prefix, version and key into a final cache key.
  339. See the :ref:`cache documentation <cache_key_transformation>`
  340. for more information.
  341. In this example, a filesystem backend is being configured with a timeout
  342. of 60 seconds, and a maximum capacity of 1000 items::
  343. CACHES = {
  344. 'default': {
  345. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  346. 'LOCATION': '/var/tmp/django_cache',
  347. 'TIMEOUT': 60,
  348. 'OPTIONS': {
  349. 'MAX_ENTRIES': 1000
  350. }
  351. }
  352. }
  353. Here's an example configuration for a ``pylibmc`` based backend that enables
  354. the binary protocol, SASL authentication, and the ``ketama`` behavior mode::
  355. CACHES = {
  356. 'default': {
  357. 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
  358. 'LOCATION': '127.0.0.1:11211',
  359. 'OPTIONS': {
  360. 'binary': True,
  361. 'username': 'user',
  362. 'password': 'pass',
  363. 'behaviors': {
  364. 'ketama': True,
  365. }
  366. }
  367. }
  368. }
  369. Here's an example configuration for a ``pymemcache`` based backend that enables
  370. client pooling (which may improve performance by keeping clients connected),
  371. treats memcache/network errors as cache misses, and sets the ``TCP_NODELAY``
  372. flag on the connection's socket::
  373. CACHES = {
  374. 'default': {
  375. 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
  376. 'LOCATION': '127.0.0.1:11211',
  377. 'OPTIONS': {
  378. 'no_delay': True,
  379. 'ignore_exc': True,
  380. 'max_pool_size': 4,
  381. 'use_pooling': True,
  382. }
  383. }
  384. }
  385. .. _the-per-site-cache:
  386. The per-site cache
  387. ==================
  388. Once the cache is set up, the simplest way to use caching is to cache your
  389. entire site. You'll need to add
  390. ``'django.middleware.cache.UpdateCacheMiddleware'`` and
  391. ``'django.middleware.cache.FetchFromCacheMiddleware'`` to your
  392. :setting:`MIDDLEWARE` setting, as in this example::
  393. MIDDLEWARE = [
  394. 'django.middleware.cache.UpdateCacheMiddleware',
  395. 'django.middleware.common.CommonMiddleware',
  396. 'django.middleware.cache.FetchFromCacheMiddleware',
  397. ]
  398. .. note::
  399. No, that's not a typo: the "update" middleware must be first in the list,
  400. and the "fetch" middleware must be last. The details are a bit obscure, but
  401. see `Order of MIDDLEWARE`_ below if you'd like the full story.
  402. Then, add the following required settings to your Django settings file:
  403. * :setting:`CACHE_MIDDLEWARE_ALIAS` -- The cache alias to use for storage.
  404. * :setting:`CACHE_MIDDLEWARE_SECONDS` -- The number of seconds each page should
  405. be cached.
  406. * :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` -- If the cache is shared across
  407. multiple sites using the same Django installation, set this to the name of
  408. the site, or some other string that is unique to this Django instance, to
  409. prevent key collisions. Use an empty string if you don't care.
  410. ``FetchFromCacheMiddleware`` caches GET and HEAD responses with status 200,
  411. where the request and response headers allow. Responses to requests for the same
  412. URL with different query parameters are considered to be unique pages and are
  413. cached separately. This middleware expects that a HEAD request is answered with
  414. the same response headers as the corresponding GET request; in which case it can
  415. return a cached GET response for HEAD request.
  416. Additionally, ``UpdateCacheMiddleware`` automatically sets a few headers in
  417. each :class:`~django.http.HttpResponse` which affect :ref:`downstream caches
  418. <downstream-caches>`:
  419. * Sets the ``Expires`` header to the current date/time plus the defined
  420. :setting:`CACHE_MIDDLEWARE_SECONDS`.
  421. * Sets the ``Cache-Control`` header to give a max age for the page --
  422. again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.
  423. See :doc:`/topics/http/middleware` for more on middleware.
  424. If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
  425. its ``Cache-Control`` header) then the page will be cached until the expiry
  426. time, rather than :setting:`CACHE_MIDDLEWARE_SECONDS`. Using the decorators in
  427. ``django.views.decorators.cache`` you can easily set a view's expiry time
  428. (using the :func:`~django.views.decorators.cache.cache_control` decorator) or
  429. disable caching for a view (using the
  430. :func:`~django.views.decorators.cache.never_cache` decorator). See the
  431. `using other headers`__ section for more on these decorators.
  432. .. _i18n-cache-key:
  433. If :setting:`USE_I18N` is set to ``True`` then the generated cache key will
  434. include the name of the active :term:`language<language code>` -- see also
  435. :ref:`how-django-discovers-language-preference`). This allows you to easily
  436. cache multilingual sites without having to create the cache key yourself.
  437. Cache keys also include the :ref:`current time zone
  438. <default-current-time-zone>` when :setting:`USE_TZ` is set to ``True``.
  439. __ `Controlling cache: Using other headers`_
  440. The per-view cache
  441. ==================
  442. .. function:: django.views.decorators.cache.cache_page
  443. A more granular way to use the caching framework is by caching the output of
  444. individual views. ``django.views.decorators.cache`` defines a ``cache_page``
  445. decorator that will automatically cache the view's response for you::
  446. from django.views.decorators.cache import cache_page
  447. @cache_page(60 * 15)
  448. def my_view(request):
  449. ...
  450. ``cache_page`` takes a single argument: the cache timeout, in seconds. In the
  451. above example, the result of the ``my_view()`` view will be cached for 15
  452. minutes. (Note that we've written it as ``60 * 15`` for the purpose of
  453. readability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes
  454. multiplied by 60 seconds per minute.)
  455. The cache timeout set by ``cache_page`` takes precedence over the ``max-age``
  456. directive from the ``Cache-Control`` header.
  457. The per-view cache, like the per-site cache, is keyed off of the URL. If
  458. multiple URLs point at the same view, each URL will be cached separately.
  459. Continuing the ``my_view`` example, if your URLconf looks like this::
  460. urlpatterns = [
  461. path('foo/<int:code>/', my_view),
  462. ]
  463. then requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as
  464. you may expect. But once a particular URL (e.g., ``/foo/23/``) has been
  465. requested, subsequent requests to that URL will use the cache.
  466. ``cache_page`` can also take an optional keyword argument, ``cache``,
  467. which directs the decorator to use a specific cache (from your
  468. :setting:`CACHES` setting) when caching view results. By default, the
  469. ``default`` cache will be used, but you can specify any cache you
  470. want::
  471. @cache_page(60 * 15, cache="special_cache")
  472. def my_view(request):
  473. ...
  474. You can also override the cache prefix on a per-view basis. ``cache_page``
  475. takes an optional keyword argument, ``key_prefix``,
  476. which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`
  477. setting for the middleware. It can be used like this::
  478. @cache_page(60 * 15, key_prefix="site1")
  479. def my_view(request):
  480. ...
  481. The ``key_prefix`` and ``cache`` arguments may be specified together. The
  482. ``key_prefix`` argument and the :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`
  483. specified under :setting:`CACHES` will be concatenated.
  484. Additionally, ``cache_page`` automatically sets ``Cache-Control`` and
  485. ``Expires`` headers in the response which affect :ref:`downstream caches
  486. <downstream-caches>`.
  487. .. versionchanged:: 3.1
  488. In older versions, the ``max-age`` directive from the ``Cache-Control``
  489. header had precedence over the cache timeout set by ``cache_page``.
  490. Specifying per-view cache in the URLconf
  491. ----------------------------------------
  492. The examples in the previous section have hard-coded the fact that the view is
  493. cached, because ``cache_page`` alters the ``my_view`` function in place. This
  494. approach couples your view to the cache system, which is not ideal for several
  495. reasons. For instance, you might want to reuse the view functions on another,
  496. cache-less site, or you might want to distribute the views to people who might
  497. want to use them without being cached. The solution to these problems is to
  498. specify the per-view cache in the URLconf rather than next to the view functions
  499. themselves.
  500. You can do so by wrapping the view function with ``cache_page`` when you refer
  501. to it in the URLconf. Here's the old URLconf from earlier::
  502. urlpatterns = [
  503. path('foo/<int:code>/', my_view),
  504. ]
  505. Here's the same thing, with ``my_view`` wrapped in ``cache_page``::
  506. from django.views.decorators.cache import cache_page
  507. urlpatterns = [
  508. path('foo/<int:code>/', cache_page(60 * 15)(my_view)),
  509. ]
  510. .. templatetag:: cache
  511. Template fragment caching
  512. =========================
  513. If you're after even more control, you can also cache template fragments using
  514. the ``cache`` template tag. To give your template access to this tag, put
  515. ``{% load cache %}`` near the top of your template.
  516. The ``{% cache %}`` template tag caches the contents of the block for a given
  517. amount of time. It takes at least two arguments: the cache timeout, in seconds,
  518. and the name to give the cache fragment. The fragment is cached forever if
  519. timeout is ``None``. The name will be taken as is, do not use a variable. For
  520. example:
  521. .. code-block:: html+django
  522. {% load cache %}
  523. {% cache 500 sidebar %}
  524. .. sidebar ..
  525. {% endcache %}
  526. Sometimes you might want to cache multiple copies of a fragment depending on
  527. some dynamic data that appears inside the fragment. For example, you might want a
  528. separate cached copy of the sidebar used in the previous example for every user
  529. of your site. Do this by passing one or more additional arguments, which may be
  530. variables with or without filters, to the ``{% cache %}`` template tag to
  531. uniquely identify the cache fragment:
  532. .. code-block:: html+django
  533. {% load cache %}
  534. {% cache 500 sidebar request.user.username %}
  535. .. sidebar for logged in user ..
  536. {% endcache %}
  537. If :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will
  538. :ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template
  539. tag you could use one of the
  540. :ref:`translation-specific variables<template-translation-vars>` available in
  541. templates to achieve the same result:
  542. .. code-block:: html+django
  543. {% load i18n %}
  544. {% load cache %}
  545. {% get_current_language as LANGUAGE_CODE %}
  546. {% cache 600 welcome LANGUAGE_CODE %}
  547. {% translate "Welcome to example.com" %}
  548. {% endcache %}
  549. The cache timeout can be a template variable, as long as the template variable
  550. resolves to an integer value. For example, if the template variable
  551. ``my_timeout`` is set to the value ``600``, then the following two examples are
  552. equivalent:
  553. .. code-block:: html+django
  554. {% cache 600 sidebar %} ... {% endcache %}
  555. {% cache my_timeout sidebar %} ... {% endcache %}
  556. This feature is useful in avoiding repetition in templates. You can set the
  557. timeout in a variable, in one place, and reuse that value.
  558. By default, the cache tag will try to use the cache called "template_fragments".
  559. If no such cache exists, it will fall back to using the default cache. You may
  560. select an alternate cache backend to use with the ``using`` keyword argument,
  561. which must be the last argument to the tag.
  562. .. code-block:: html+django
  563. {% cache 300 local-thing ... using="localcache" %}
  564. It is considered an error to specify a cache name that is not configured.
  565. .. function:: django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None)
  566. If you want to obtain the cache key used for a cached fragment, you can use
  567. ``make_template_fragment_key``. ``fragment_name`` is the same as second argument
  568. to the ``cache`` template tag; ``vary_on`` is a list of all additional arguments
  569. passed to the tag. This function can be useful for invalidating or overwriting
  570. a cached item, for example:
  571. .. code-block:: pycon
  572. >>> from django.core.cache import cache
  573. >>> from django.core.cache.utils import make_template_fragment_key
  574. # cache key for {% cache 500 sidebar username %}
  575. >>> key = make_template_fragment_key('sidebar', [username])
  576. >>> cache.delete(key) # invalidates cached template fragment
  577. True
  578. .. _low-level-cache-api:
  579. The low-level cache API
  580. =======================
  581. .. highlight:: python
  582. Sometimes, caching an entire rendered page doesn't gain you very much and is,
  583. in fact, inconvenient overkill.
  584. Perhaps, for instance, your site includes a view whose results depend on
  585. several expensive queries, the results of which change at different intervals.
  586. In this case, it would not be ideal to use the full-page caching that the
  587. per-site or per-view cache strategies offer, because you wouldn't want to
  588. cache the entire result (since some of the data changes often), but you'd still
  589. want to cache the results that rarely change.
  590. For cases like this, Django exposes a low-level cache API. You can use this API
  591. to store objects in the cache with any level of granularity you like. You can
  592. cache any Python object that can be pickled safely: strings, dictionaries,
  593. lists of model objects, and so forth. (Most common Python objects can be
  594. pickled; refer to the Python documentation for more information about
  595. pickling.)
  596. Accessing the cache
  597. -------------------
  598. .. data:: django.core.cache.caches
  599. You can access the caches configured in the :setting:`CACHES` setting
  600. through a dict-like object: ``django.core.cache.caches``. Repeated
  601. requests for the same alias in the same thread will return the same
  602. object.
  603. >>> from django.core.cache import caches
  604. >>> cache1 = caches['myalias']
  605. >>> cache2 = caches['myalias']
  606. >>> cache1 is cache2
  607. True
  608. If the named key does not exist, ``InvalidCacheBackendError`` will be
  609. raised.
  610. To provide thread-safety, a different instance of the cache backend will
  611. be returned for each thread.
  612. .. data:: django.core.cache.cache
  613. As a shortcut, the default cache is available as
  614. ``django.core.cache.cache``::
  615. >>> from django.core.cache import cache
  616. This object is equivalent to ``caches['default']``.
  617. Basic usage
  618. -----------
  619. .. currentmodule:: django.core.caches
  620. The basic interface is:
  621. .. method:: cache.set(key, value, timeout=DEFAULT_TIMEOUT, version=None)
  622. >>> cache.set('my_key', 'hello, world!', 30)
  623. .. method:: cache.get(key, default=None, version=None)
  624. >>> cache.get('my_key')
  625. 'hello, world!'
  626. ``key`` should be a ``str``, and ``value`` can be any picklable Python object.
  627. The ``timeout`` argument is optional and defaults to the ``timeout`` argument
  628. of the appropriate backend in the :setting:`CACHES` setting (explained above).
  629. It's the number of seconds the value should be stored in the cache. Passing in
  630. ``None`` for ``timeout`` will cache the value forever. A ``timeout`` of ``0``
  631. won't cache the value.
  632. If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
  633. >>> # Wait 30 seconds for 'my_key' to expire...
  634. >>> cache.get('my_key')
  635. None
  636. If you need to determine whether the object exists in the cache and you have
  637. stored a literal value ``None``, use a sentinel object as the default::
  638. >>> sentinel = object()
  639. >>> cache.get('my_key', sentinel) is sentinel
  640. False
  641. >>> # Wait 30 seconds for 'my_key' to expire...
  642. >>> cache.get('my_key', sentinel) is sentinel
  643. True
  644. .. admonition:: ``MemcachedCache``
  645. Due to a ``python-memcached`` limitation, it's not possible to distinguish
  646. between stored ``None`` value and a cache miss signified by a return value
  647. of ``None`` on the deprecated ``MemcachedCache`` backend.
  648. ``cache.get()`` can take a ``default`` argument. This specifies which value to
  649. return if the object doesn't exist in the cache::
  650. >>> cache.get('my_key', 'has expired')
  651. 'has expired'
  652. .. method:: cache.add(key, value, timeout=DEFAULT_TIMEOUT, version=None)
  653. To add a key only if it doesn't already exist, use the ``add()`` method.
  654. It takes the same parameters as ``set()``, but it will not attempt to
  655. update the cache if the key specified is already present::
  656. >>> cache.set('add_key', 'Initial value')
  657. >>> cache.add('add_key', 'New value')
  658. >>> cache.get('add_key')
  659. 'Initial value'
  660. If you need to know whether ``add()`` stored a value in the cache, you can
  661. check the return value. It will return ``True`` if the value was stored,
  662. ``False`` otherwise.
  663. .. method:: cache.get_or_set(key, default, timeout=DEFAULT_TIMEOUT, version=None)
  664. If you want to get a key's value or set a value if the key isn't in the cache,
  665. there is the ``get_or_set()`` method. It takes the same parameters as ``get()``
  666. but the default is set as the new cache value for that key, rather than
  667. returned::
  668. >>> cache.get('my_new_key') # returns None
  669. >>> cache.get_or_set('my_new_key', 'my new value', 100)
  670. 'my new value'
  671. You can also pass any callable as a *default* value::
  672. >>> import datetime
  673. >>> cache.get_or_set('some-timestamp-key', datetime.datetime.now)
  674. datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)
  675. .. method:: cache.get_many(keys, version=None)
  676. There's also a ``get_many()`` interface that only hits the cache once.
  677. ``get_many()`` returns a dictionary with all the keys you asked for that
  678. actually exist in the cache (and haven't expired)::
  679. >>> cache.set('a', 1)
  680. >>> cache.set('b', 2)
  681. >>> cache.set('c', 3)
  682. >>> cache.get_many(['a', 'b', 'c'])
  683. {'a': 1, 'b': 2, 'c': 3}
  684. .. method:: cache.set_many(dict, timeout)
  685. To set multiple values more efficiently, use ``set_many()`` to pass a dictionary
  686. of key-value pairs::
  687. >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})
  688. >>> cache.get_many(['a', 'b', 'c'])
  689. {'a': 1, 'b': 2, 'c': 3}
  690. Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.
  691. On supported backends (memcached), ``set_many()`` returns a list of keys that
  692. failed to be inserted.
  693. .. method:: cache.delete(key, version=None)
  694. You can delete keys explicitly with ``delete()`` to clear the cache for a
  695. particular object::
  696. >>> cache.delete('a')
  697. True
  698. ``delete()`` returns ``True`` if the key was successfully deleted, ``False``
  699. otherwise.
  700. .. versionchanged:: 3.1
  701. The boolean return value was added.
  702. .. method:: cache.delete_many(keys, version=None)
  703. If you want to clear a bunch of keys at once, ``delete_many()`` can take a list
  704. of keys to be cleared::
  705. >>> cache.delete_many(['a', 'b', 'c'])
  706. .. method:: cache.clear()
  707. Finally, if you want to delete all the keys in the cache, use
  708. ``cache.clear()``. Be careful with this; ``clear()`` will remove *everything*
  709. from the cache, not just the keys set by your application. ::
  710. >>> cache.clear()
  711. .. method:: cache.touch(key, timeout=DEFAULT_TIMEOUT, version=None)
  712. ``cache.touch()`` sets a new expiration for a key. For example, to update a key
  713. to expire 10 seconds from now::
  714. >>> cache.touch('a', 10)
  715. True
  716. Like other methods, the ``timeout`` argument is optional and defaults to the
  717. ``TIMEOUT`` option of the appropriate backend in the :setting:`CACHES` setting.
  718. ``touch()`` returns ``True`` if the key was successfully touched, ``False``
  719. otherwise.
  720. .. method:: cache.incr(key, delta=1, version=None)
  721. .. method:: cache.decr(key, delta=1, version=None)
  722. You can also increment or decrement a key that already exists using the
  723. ``incr()`` or ``decr()`` methods, respectively. By default, the existing cache
  724. value will be incremented or decremented by 1. Other increment/decrement values
  725. can be specified by providing an argument to the increment/decrement call. A
  726. ValueError will be raised if you attempt to increment or decrement a
  727. nonexistent cache key.::
  728. >>> cache.set('num', 1)
  729. >>> cache.incr('num')
  730. 2
  731. >>> cache.incr('num', 10)
  732. 12
  733. >>> cache.decr('num')
  734. 11
  735. >>> cache.decr('num', 5)
  736. 6
  737. .. note::
  738. ``incr()``/``decr()`` methods are not guaranteed to be atomic. On those
  739. backends that support atomic increment/decrement (most notably, the
  740. memcached backend), increment and decrement operations will be atomic.
  741. However, if the backend doesn't natively provide an increment/decrement
  742. operation, it will be implemented using a two-step retrieve/update.
  743. .. method:: cache.close()
  744. You can close the connection to your cache with ``close()`` if implemented by
  745. the cache backend.
  746. >>> cache.close()
  747. .. note::
  748. For caches that don't implement ``close`` methods it is a no-op.
  749. .. _cache_key_prefixing:
  750. Cache key prefixing
  751. -------------------
  752. If you are sharing a cache instance between servers, or between your
  753. production and development environments, it's possible for data cached
  754. by one server to be used by another server. If the format of cached
  755. data is different between servers, this can lead to some very hard to
  756. diagnose problems.
  757. To prevent this, Django provides the ability to prefix all cache keys
  758. used by a server. When a particular cache key is saved or retrieved,
  759. Django will automatically prefix the cache key with the value of the
  760. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` cache setting.
  761. By ensuring each Django instance has a different
  762. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`, you can ensure that there will be no
  763. collisions in cache values.
  764. .. _cache_versioning:
  765. Cache versioning
  766. ----------------
  767. When you change running code that uses cached values, you may need to
  768. purge any existing cached values. The easiest way to do this is to
  769. flush the entire cache, but this can lead to the loss of cache values
  770. that are still valid and useful.
  771. Django provides a better way to target individual cache values.
  772. Django's cache framework has a system-wide version identifier,
  773. specified using the :setting:`VERSION <CACHES-VERSION>` cache setting.
  774. The value of this setting is automatically combined with the cache
  775. prefix and the user-provided cache key to obtain the final cache key.
  776. By default, any key request will automatically include the site
  777. default cache key version. However, the primitive cache functions all
  778. include a ``version`` argument, so you can specify a particular cache
  779. key version to set or get. For example::
  780. >>> # Set version 2 of a cache key
  781. >>> cache.set('my_key', 'hello world!', version=2)
  782. >>> # Get the default version (assuming version=1)
  783. >>> cache.get('my_key')
  784. None
  785. >>> # Get version 2 of the same key
  786. >>> cache.get('my_key', version=2)
  787. 'hello world!'
  788. The version of a specific key can be incremented and decremented using
  789. the ``incr_version()`` and ``decr_version()`` methods. This
  790. enables specific keys to be bumped to a new version, leaving other
  791. keys unaffected. Continuing our previous example::
  792. >>> # Increment the version of 'my_key'
  793. >>> cache.incr_version('my_key')
  794. >>> # The default version still isn't available
  795. >>> cache.get('my_key')
  796. None
  797. # Version 2 isn't available, either
  798. >>> cache.get('my_key', version=2)
  799. None
  800. >>> # But version 3 *is* available
  801. >>> cache.get('my_key', version=3)
  802. 'hello world!'
  803. .. _cache_key_transformation:
  804. Cache key transformation
  805. ------------------------
  806. As described in the previous two sections, the cache key provided by a
  807. user is not used verbatim -- it is combined with the cache prefix and
  808. key version to provide a final cache key. By default, the three parts
  809. are joined using colons to produce a final string::
  810. def make_key(key, key_prefix, version):
  811. return '%s:%s:%s' % (key_prefix, version, key)
  812. If you want to combine the parts in different ways, or apply other
  813. processing to the final key (e.g., taking a hash digest of the key
  814. parts), you can provide a custom key function.
  815. The :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting
  816. specifies a dotted-path to a function matching the prototype of
  817. ``make_key()`` above. If provided, this custom key function will
  818. be used instead of the default key combining function.
  819. Cache key warnings
  820. ------------------
  821. Memcached, the most commonly-used production cache backend, does not allow
  822. cache keys longer than 250 characters or containing whitespace or control
  823. characters, and using such keys will cause an exception. To encourage
  824. cache-portable code and minimize unpleasant surprises, the other built-in cache
  825. backends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``)
  826. if a key is used that would cause an error on memcached.
  827. If you are using a production backend that can accept a wider range of keys (a
  828. custom backend, or one of the non-memcached built-in backends), and want to use
  829. this wider range without warnings, you can silence ``CacheKeyWarning`` with
  830. this code in the ``management`` module of one of your
  831. :setting:`INSTALLED_APPS`::
  832. import warnings
  833. from django.core.cache import CacheKeyWarning
  834. warnings.simplefilter("ignore", CacheKeyWarning)
  835. If you want to instead provide custom key validation logic for one of the
  836. built-in backends, you can subclass it, override just the ``validate_key``
  837. method, and follow the instructions for `using a custom cache backend`_. For
  838. instance, to do this for the ``locmem`` backend, put this code in a module::
  839. from django.core.cache.backends.locmem import LocMemCache
  840. class CustomLocMemCache(LocMemCache):
  841. def validate_key(self, key):
  842. """Custom validation, raising exceptions or warnings as needed."""
  843. ...
  844. ...and use the dotted Python path to this class in the
  845. :setting:`BACKEND <CACHES-BACKEND>` portion of your :setting:`CACHES` setting.
  846. .. _downstream-caches:
  847. Downstream caches
  848. =================
  849. So far, this document has focused on caching your *own* data. But another type
  850. of caching is relevant to Web development, too: caching performed by
  851. "downstream" caches. These are systems that cache pages for users even before
  852. the request reaches your website.
  853. Here are a few examples of downstream caches:
  854. * Your ISP may cache certain pages, so if you requested a page from
  855. https://example.com/, your ISP would send you the page without having to
  856. access example.com directly. The maintainers of example.com have no
  857. knowledge of this caching; the ISP sits between example.com and your Web
  858. browser, handling all of the caching transparently.
  859. * Your Django website may sit behind a *proxy cache*, such as Squid Web
  860. Proxy Cache (http://www.squid-cache.org/), that caches pages for
  861. performance. In this case, each request first would be handled by the
  862. proxy, and it would be passed to your application only if needed.
  863. * Your Web browser caches pages, too. If a Web page sends out the
  864. appropriate headers, your browser will use the local cached copy for
  865. subsequent requests to that page, without even contacting the Web page
  866. again to see whether it has changed.
  867. Downstream caching is a nice efficiency boost, but there's a danger to it:
  868. Many Web pages' contents differ based on authentication and a host of other
  869. variables, and cache systems that blindly save pages based purely on URLs could
  870. expose incorrect or sensitive data to subsequent visitors to those pages.
  871. For example, if you operate a Web email system, then the contents of the
  872. "inbox" page depend on which user is logged in. If an ISP blindly cached your
  873. site, then the first user who logged in through that ISP would have their
  874. user-specific inbox page cached for subsequent visitors to the site. That's
  875. not cool.
  876. Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
  877. exist to instruct downstream caches to differ their cache contents depending on
  878. designated variables, and to tell caching mechanisms not to cache particular
  879. pages. We'll look at some of these headers in the sections that follow.
  880. .. _using-vary-headers:
  881. Using ``Vary`` headers
  882. ======================
  883. The ``Vary`` header defines which request headers a cache
  884. mechanism should take into account when building its cache key. For example, if
  885. the contents of a Web page depend on a user's language preference, the page is
  886. said to "vary on language."
  887. By default, Django's cache system creates its cache keys using the requested
  888. fully-qualified URL -- e.g.,
  889. ``"https://www.example.com/stories/2005/?order_by=author"``. This means every
  890. request to that URL will use the same cached version, regardless of user-agent
  891. differences such as cookies or language preferences. However, if this page
  892. produces different content based on some difference in request headers -- such
  893. as a cookie, or a language, or a user-agent -- you'll need to use the ``Vary``
  894. header to tell caching mechanisms that the page output depends on those things.
  895. To do this in Django, use the convenient
  896. :func:`django.views.decorators.vary.vary_on_headers` view decorator, like so::
  897. from django.views.decorators.vary import vary_on_headers
  898. @vary_on_headers('User-Agent')
  899. def my_view(request):
  900. ...
  901. In this case, a caching mechanism (such as Django's own cache middleware) will
  902. cache a separate version of the page for each unique user-agent.
  903. The advantage to using the ``vary_on_headers`` decorator rather than manually
  904. setting the ``Vary`` header (using something like ``response.headers['Vary'] =
  905. 'user-agent'``) is that the decorator *adds* to the ``Vary`` header (which may
  906. already exist), rather than setting it from scratch and potentially overriding
  907. anything that was already in there.
  908. You can pass multiple headers to ``vary_on_headers()``::
  909. @vary_on_headers('User-Agent', 'Cookie')
  910. def my_view(request):
  911. ...
  912. This tells downstream caches to vary on *both*, which means each combination of
  913. user-agent and cookie will get its own cache value. For example, a request with
  914. the user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered
  915. different from a request with the user-agent ``Mozilla`` and the cookie value
  916. ``foo=ham``.
  917. Because varying on cookie is so common, there's a
  918. :func:`django.views.decorators.vary.vary_on_cookie` decorator. These two views
  919. are equivalent::
  920. @vary_on_cookie
  921. def my_view(request):
  922. ...
  923. @vary_on_headers('Cookie')
  924. def my_view(request):
  925. ...
  926. The headers you pass to ``vary_on_headers`` are not case sensitive;
  927. ``"User-Agent"`` is the same thing as ``"user-agent"``.
  928. You can also use a helper function, :func:`django.utils.cache.patch_vary_headers`,
  929. directly. This function sets, or adds to, the ``Vary header``. For example::
  930. from django.shortcuts import render
  931. from django.utils.cache import patch_vary_headers
  932. def my_view(request):
  933. ...
  934. response = render(request, 'template_name', context)
  935. patch_vary_headers(response, ['Cookie'])
  936. return response
  937. ``patch_vary_headers`` takes an :class:`~django.http.HttpResponse` instance as
  938. its first argument and a list/tuple of case-insensitive header names as its
  939. second argument.
  940. For more on Vary headers, see the :rfc:`official Vary spec
  941. <7231#section-7.1.4>`.
  942. Controlling cache: Using other headers
  943. ======================================
  944. Other problems with caching are the privacy of data and the question of where
  945. data should be stored in a cascade of caches.
  946. A user usually faces two kinds of caches: their own browser cache (a private
  947. cache) and their provider's cache (a public cache). A public cache is used by
  948. multiple users and controlled by someone else. This poses problems with
  949. sensitive data--you don't want, say, your bank account number stored in a
  950. public cache. So Web applications need a way to tell caches which data is
  951. private and which is public.
  952. The solution is to indicate a page's cache should be "private." To do this in
  953. Django, use the :func:`~django.views.decorators.cache.cache_control` view
  954. decorator. Example::
  955. from django.views.decorators.cache import cache_control
  956. @cache_control(private=True)
  957. def my_view(request):
  958. ...
  959. This decorator takes care of sending out the appropriate HTTP header behind the
  960. scenes.
  961. Note that the cache control settings "private" and "public" are mutually
  962. exclusive. The decorator ensures that the "public" directive is removed if
  963. "private" should be set (and vice versa). An example use of the two directives
  964. would be a blog site that offers both private and public entries. Public
  965. entries may be cached on any shared cache. The following code uses
  966. :func:`~django.utils.cache.patch_cache_control`, the manual way to modify the
  967. cache control header (it is internally called by the
  968. :func:`~django.views.decorators.cache.cache_control` decorator)::
  969. from django.views.decorators.cache import patch_cache_control
  970. from django.views.decorators.vary import vary_on_cookie
  971. @vary_on_cookie
  972. def list_blog_entries_view(request):
  973. if request.user.is_anonymous:
  974. response = render_only_public_entries()
  975. patch_cache_control(response, public=True)
  976. else:
  977. response = render_private_and_public_entries(request.user)
  978. patch_cache_control(response, private=True)
  979. return response
  980. You can control downstream caches in other ways as well (see :rfc:`7234` for
  981. details on HTTP caching). For example, even if you don't use Django's
  982. server-side cache framework, you can still tell clients to cache a view for a
  983. certain amount of time with the :rfc:`max-age <7234#section-5.2.2.8>`
  984. directive::
  985. from django.views.decorators.cache import cache_control
  986. @cache_control(max_age=3600)
  987. def my_view(request):
  988. ...
  989. (If you *do* use the caching middleware, it already sets the ``max-age`` with
  990. the value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. In that case,
  991. the custom ``max_age`` from the
  992. :func:`~django.views.decorators.cache.cache_control` decorator will take
  993. precedence, and the header values will be merged correctly.)
  994. Any valid ``Cache-Control`` response directive is valid in ``cache_control()``.
  995. Here are some more examples:
  996. * ``no_transform=True``
  997. * ``must_revalidate=True``
  998. * ``stale_while_revalidate=num_seconds``
  999. * ``no_cache=True``
  1000. The full list of known directives can be found in the `IANA registry`_
  1001. (note that not all of them apply to responses).
  1002. .. _IANA registry: https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml
  1003. If you want to use headers to disable caching altogether,
  1004. :func:`~django.views.decorators.cache.never_cache` is a view decorator that
  1005. adds headers to ensure the response won't be cached by browsers or other
  1006. caches. Example::
  1007. from django.views.decorators.cache import never_cache
  1008. @never_cache
  1009. def myview(request):
  1010. ...
  1011. Order of ``MIDDLEWARE``
  1012. =======================
  1013. If you use caching middleware, it's important to put each half in the right
  1014. place within the :setting:`MIDDLEWARE` setting. That's because the cache
  1015. middleware needs to know which headers by which to vary the cache storage.
  1016. Middleware always adds something to the ``Vary`` response header when it can.
  1017. ``UpdateCacheMiddleware`` runs during the response phase, where middleware is
  1018. run in reverse order, so an item at the top of the list runs *last* during the
  1019. response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
  1020. appears *before* any other middleware that might add something to the ``Vary``
  1021. header. The following middleware modules do so:
  1022. * ``SessionMiddleware`` adds ``Cookie``
  1023. * ``GZipMiddleware`` adds ``Accept-Encoding``
  1024. * ``LocaleMiddleware`` adds ``Accept-Language``
  1025. ``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
  1026. where middleware is applied first-to-last, so an item at the top of the list
  1027. runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
  1028. needs to run after other middleware updates the ``Vary`` header, so
  1029. ``FetchFromCacheMiddleware`` must be *after* any item that does so.