cache.txt 49 KB

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