cache.txt 55 KB

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