cache.txt 56 KB

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