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