cache.txt 55 KB

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