cache.txt 51 KB

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