cache.txt 56 KB

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