cache.txt 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. .. _topics-cache:
  2. ========================
  3. Django's cache framework
  4. ========================
  5. A fundamental trade-off in dynamic Web sites 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. For most Web applications, this overhead isn't a big deal. Most Web
  12. applications aren't washingtonpost.com or slashdot.org; they're simply small-
  13. to medium-sized sites with so-so traffic. But for medium- to high-traffic
  14. sites, it's essential to cut as much overhead as possible.
  15. That's where caching comes in.
  16. To cache something is to save the result of an expensive calculation so that
  17. you don't have to perform the calculation next time. Here's some pseudocode
  18. explaining how this would work for a dynamically generated Web page::
  19. given a URL, try finding that page in the cache
  20. if the page is in the cache:
  21. return the cached page
  22. else:
  23. generate the page
  24. save the generated page in the cache (for next time)
  25. return the generated page
  26. Django comes with a robust cache system that lets you save dynamic pages so
  27. they don't have to be calculated for each request. For convenience, Django
  28. offers different levels of cache granularity: You can cache the output of
  29. specific views, you can cache only the pieces that are difficult to produce, or
  30. you can cache your entire site.
  31. Django also works well with "upstream" caches, such as Squid
  32. (http://www.squid-cache.org/) and browser-based caches. These are the types of
  33. caches that you don't directly control but to which you can provide hints (via
  34. HTTP headers) about which parts of your site should be cached, and how.
  35. Setting up the cache
  36. ====================
  37. The cache system requires a small amount of setup. Namely, you have to tell it
  38. where your cached data should live -- whether in a database, on the filesystem
  39. or directly in memory. This is an important decision that affects your cache's
  40. performance; yes, some cache types are faster than others.
  41. Your cache preference goes in the ``CACHE_BACKEND`` setting in your settings
  42. file. Here's an explanation of all available values for ``CACHE_BACKEND``.
  43. Memcached
  44. ---------
  45. By far the fastest, most efficient type of cache available to Django, Memcached
  46. is an entirely memory-based cache framework originally developed to handle high
  47. loads at LiveJournal.com and subsequently open-sourced by Danga Interactive.
  48. It's used by sites such as Facebook and Wikipedia to reduce database access and
  49. dramatically increase site performance.
  50. Memcached is available for free at http://danga.com/memcached/ . It runs as a
  51. daemon and is allotted a specified amount of RAM. All it does is provide a
  52. fast interface for adding, retrieving and deleting arbitrary data in the cache.
  53. All data is stored directly in memory, so there's no overhead of database or
  54. filesystem usage.
  55. After installing Memcached itself, you'll need to install
  56. ``python-memcached``, which provides Python bindings to Memcached.
  57. This is available at ftp://ftp.tummy.com/pub/python-memcached/
  58. .. versionchanged:: 1.2
  59. In Django 1.0 and 1.1, you could also use ``cmemcache`` as a binding.
  60. However, support for this library was deprecated in 1.2 due to
  61. a lack of maintenance on the ``cmemcache`` library itself. Support for
  62. ``cmemcache`` will be removed completely in Django 1.4.
  63. To use Memcached with Django, set ``CACHE_BACKEND`` to
  64. ``memcached://ip:port/``, where ``ip`` is the IP address of the Memcached
  65. daemon and ``port`` is the port on which Memcached is running.
  66. In this example, Memcached is running on localhost (127.0.0.1) port 11211::
  67. CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
  68. One excellent feature of Memcached is its ability to share cache over multiple
  69. servers. This means you can run Memcached daemons on multiple machines, and the
  70. program will treat the group of machines as a *single* cache, without the need
  71. to duplicate cache values on each machine. To take advantage of this feature,
  72. include all server addresses in ``CACHE_BACKEND``, separated by semicolons.
  73. In this example, the cache is shared over Memcached instances running on IP
  74. address 172.19.26.240 and 172.19.26.242, both on port 11211::
  75. CACHE_BACKEND = 'memcached://172.19.26.240:11211;172.19.26.242:11211/'
  76. In the following example, the cache is shared over Memcached instances running
  77. on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
  78. 172.19.26.244 (port 11213)::
  79. CACHE_BACKEND = 'memcached://172.19.26.240:11211;172.19.26.242:11212;172.19.26.244:11213/'
  80. A final point about Memcached is that memory-based caching has one
  81. disadvantage: Because the cached data is stored in memory, the data will be
  82. lost if your server crashes. Clearly, memory isn't intended for permanent data
  83. storage, so don't rely on memory-based caching as your only data storage.
  84. Without a doubt, *none* of the Django caching backends should be used for
  85. permanent storage -- they're all intended to be solutions for caching, not
  86. storage -- but we point this out here because memory-based caching is
  87. particularly temporary.
  88. Database caching
  89. ----------------
  90. To use a database table as your cache backend, first create a cache table in
  91. your database by running this command::
  92. python manage.py createcachetable [cache_table_name]
  93. ...where ``[cache_table_name]`` is the name of the database table to create.
  94. (This name can be whatever you want, as long as it's a valid table name that's
  95. not already being used in your database.) This command creates a single table
  96. in your database that is in the proper format that Django's database-cache
  97. system expects.
  98. Once you've created that database table, set your ``CACHE_BACKEND`` setting to
  99. ``"db://tablename"``, where ``tablename`` is the name of the database table.
  100. In this example, the cache table's name is ``my_cache_table``::
  101. CACHE_BACKEND = 'db://my_cache_table'
  102. The database caching backend uses the same database as specified in your
  103. settings file. You can't use a different database backend for your cache table.
  104. Database caching works best if you've got a fast, well-indexed database server.
  105. Filesystem caching
  106. ------------------
  107. To store cached items on a filesystem, use the ``"file://"`` cache type for
  108. ``CACHE_BACKEND``. For example, to store cached data in ``/var/tmp/django_cache``,
  109. use this setting::
  110. CACHE_BACKEND = 'file:///var/tmp/django_cache'
  111. Note that there are three forward slashes toward the beginning of that example.
  112. The first two are for ``file://``, and the third is the first character of the
  113. directory path, ``/var/tmp/django_cache``. If you're on Windows, put the
  114. drive letter after the ``file://``, like this::
  115. file://c:/foo/bar
  116. The directory path should be absolute -- that is, it should start at the root
  117. of your filesystem. It doesn't matter whether you put a slash at the end of the
  118. setting.
  119. Make sure the directory pointed-to by this setting exists and is readable and
  120. writable by the system user under which your Web server runs. Continuing the
  121. above example, if your server runs as the user ``apache``, make sure the
  122. directory ``/var/tmp/django_cache`` exists and is readable and writable by the
  123. user ``apache``.
  124. Each cache value will be stored as a separate file whose contents are the
  125. cache data saved in a serialized ("pickled") format, using Python's ``pickle``
  126. module. Each file's name is the cache key, escaped for safe filesystem use.
  127. Local-memory caching
  128. --------------------
  129. If you want the speed advantages of in-memory caching but don't have the
  130. capability of running Memcached, consider the local-memory cache backend. This
  131. cache is multi-process and thread-safe. To use it, set ``CACHE_BACKEND`` to
  132. ``"locmem://"``. For example::
  133. CACHE_BACKEND = 'locmem://'
  134. Note that each process will have its own private cache instance, which means no
  135. cross-process caching is possible. This obviously also means the local memory
  136. cache isn't particularly memory-efficient, so it's probably not a good choice
  137. for production environments. It's nice for development.
  138. Dummy caching (for development)
  139. -------------------------------
  140. Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
  141. just implements the cache interface without doing anything.
  142. This is useful if you have a production site that uses heavy-duty caching in
  143. various places but a development/test environment where you don't want to cache
  144. and don't want to have to change your code to special-case the latter. To
  145. activate dummy caching, set ``CACHE_BACKEND`` like so::
  146. CACHE_BACKEND = 'dummy://'
  147. Using a custom cache backend
  148. ----------------------------
  149. .. versionadded:: 1.0
  150. While Django includes support for a number of cache backends out-of-the-box,
  151. sometimes you might want to use a customized cache backend. To use an external
  152. cache backend with Django, use a Python import path as the scheme portion (the
  153. part before the initial colon) of the ``CACHE_BACKEND`` URI, like so::
  154. CACHE_BACKEND = 'path.to.backend://'
  155. If you're building your own backend, you can use the standard cache backends
  156. as reference implementations. You'll find the code in the
  157. ``django/core/cache/backends/`` directory of the Django source.
  158. Note: Without a really compelling reason, such as a host that doesn't support
  159. them, you should stick to the cache backends included with Django. They've
  160. been well-tested and are easy to use.
  161. CACHE_BACKEND arguments
  162. -----------------------
  163. Each cache backend may take arguments. They're given in query-string style on
  164. the ``CACHE_BACKEND`` setting. Valid arguments are as follows:
  165. * ``timeout``: The default timeout, in seconds, to use for the cache.
  166. This argument defaults to 300 seconds (5 minutes).
  167. * ``max_entries``: For the ``locmem``, ``filesystem`` and ``database``
  168. backends, the maximum number of entries allowed in the cache before old
  169. values are deleted. This argument defaults to 300.
  170. * ``cull_frequency``: The fraction of entries that are culled when
  171. ``max_entries`` is reached. The actual ratio is ``1/cull_frequency``, so
  172. set ``cull_frequency=2`` to cull half of the entries when ``max_entries``
  173. is reached.
  174. A value of ``0`` for ``cull_frequency`` means that the entire cache will
  175. be dumped when ``max_entries`` is reached. This makes culling *much*
  176. faster at the expense of more cache misses.
  177. In this example, ``timeout`` is set to ``60``::
  178. CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=60"
  179. In this example, ``timeout`` is ``30`` and ``max_entries`` is ``400``::
  180. CACHE_BACKEND = "locmem://?timeout=30&max_entries=400"
  181. Invalid arguments are silently ignored, as are invalid values of known
  182. arguments.
  183. The per-site cache
  184. ==================
  185. .. versionchanged:: 1.0
  186. (previous versions of Django only provided a single ``CacheMiddleware`` instead
  187. of the two pieces described below).
  188. Once the cache is set up, the simplest way to use caching is to cache your
  189. entire site. You'll need to add
  190. ``'django.middleware.cache.UpdateCacheMiddleware'`` and
  191. ``'django.middleware.cache.FetchFromCacheMiddleware'`` to your
  192. ``MIDDLEWARE_CLASSES`` setting, as in this example::
  193. MIDDLEWARE_CLASSES = (
  194. 'django.middleware.cache.UpdateCacheMiddleware',
  195. 'django.middleware.common.CommonMiddleware',
  196. 'django.middleware.cache.FetchFromCacheMiddleware',
  197. )
  198. .. note::
  199. No, that's not a typo: the "update" middleware must be first in the list,
  200. and the "fetch" middleware must be last. The details are a bit obscure, but
  201. see `Order of MIDDLEWARE_CLASSES`_ below if you'd like the full story.
  202. Then, add the following required settings to your Django settings file:
  203. * ``CACHE_MIDDLEWARE_SECONDS`` -- The number of seconds each page should be
  204. cached.
  205. * ``CACHE_MIDDLEWARE_KEY_PREFIX`` -- If the cache is shared across multiple
  206. sites using the same Django installation, set this to the name of the site,
  207. or some other string that is unique to this Django instance, to prevent key
  208. collisions. Use an empty string if you don't care.
  209. The cache middleware caches every page that doesn't have GET or POST
  210. parameters. Optionally, if the ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting is
  211. ``True``, only anonymous requests (i.e., not those made by a logged-in user)
  212. will be cached. This is a simple and effective way of disabling caching for any
  213. user-specific pages (include Django's admin interface). Note that if you use
  214. ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY``, you should make sure you've activated
  215. ``AuthenticationMiddleware``.
  216. Additionally, the cache middleware automatically sets a few headers in each
  217. ``HttpResponse``:
  218. * Sets the ``Last-Modified`` header to the current date/time when a fresh
  219. (uncached) version of the page is requested.
  220. * Sets the ``Expires`` header to the current date/time plus the defined
  221. ``CACHE_MIDDLEWARE_SECONDS``.
  222. * Sets the ``Cache-Control`` header to give a max age for the page --
  223. again, from the ``CACHE_MIDDLEWARE_SECONDS`` setting.
  224. See :ref:`topics-http-middleware` for more on middleware.
  225. .. versionadded:: 1.0
  226. If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
  227. its ``Cache-Control`` header) then the page will be cached until the expiry
  228. time, rather than ``CACHE_MIDDLEWARE_SECONDS``. Using the decorators in
  229. ``django.views.decorators.cache`` you can easily set a view's expiry time
  230. (using the ``cache_control`` decorator) or disable caching for a view (using
  231. the ``never_cache`` decorator). See the `using other headers`__ section for
  232. more on these decorators.
  233. .. _i18n-cache-key:
  234. .. versionadded:: 1.2
  235. If :setting:`USE_I18N` is set to ``True`` then the generated cache key will
  236. include the name of the active :term:`language<language code>`.
  237. This allows you to easily cache multilingual sites without having to create
  238. the cache key yourself.
  239. See :ref:`topics-i18n-deployment` for more on how Django discovers the active
  240. language.
  241. __ `Controlling cache: Using other headers`_
  242. The per-view cache
  243. ==================
  244. A more granular way to use the caching framework is by caching the output of
  245. individual views. ``django.views.decorators.cache`` defines a ``cache_page``
  246. decorator that will automatically cache the view's response for you. It's easy
  247. to use::
  248. from django.views.decorators.cache import cache_page
  249. @cache_page(60 * 15)
  250. def my_view(request):
  251. ...
  252. ``cache_page`` takes a single argument: the cache timeout, in seconds. In the
  253. above example, the result of the ``my_view()`` view will be cached for 15
  254. minutes. (Note that we've written it as ``60 * 15`` for the purpose of
  255. readability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes
  256. multiplied by 60 seconds per minute.)
  257. The per-view cache, like the per-site cache, is keyed off of the URL. If
  258. multiple URLs point at the same view, each URL will be cached separately.
  259. Continuing the ``my_view`` example, if your URLconf looks like this::
  260. urlpatterns = ('',
  261. (r'^foo/(\d{1,2})/$', my_view),
  262. )
  263. then requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as
  264. you may expect. But once a particular URL (e.g., ``/foo/23/``) has been
  265. requested, subsequent requests to that URL will use the cache.
  266. ``cache_page`` can also take an optional keyword argument, ``key_prefix``, which
  267. works in the same way as the ``CACHE_MIDDLEWARE_KEY_PREFIX`` setting for the
  268. middleware. It can be used like this::
  269. @cache_page(60 * 15, key_prefix="site1")
  270. def my_view(request):
  271. ...
  272. Specifying per-view cache in the URLconf
  273. ----------------------------------------
  274. The examples in the previous section have hard-coded the fact that the view is
  275. cached, because ``cache_page`` alters the ``my_view`` function in place. This
  276. approach couples your view to the cache system, which is not ideal for several
  277. reasons. For instance, you might want to reuse the view functions on another,
  278. cache-less site, or you might want to distribute the views to people who might
  279. want to use them without being cached. The solution to these problems is to
  280. specify the per-view cache in the URLconf rather than next to the view functions
  281. themselves.
  282. Doing so is easy: simply wrap the view function with ``cache_page`` when you
  283. refer to it in the URLconf. Here's the old URLconf from earlier::
  284. urlpatterns = ('',
  285. (r'^foo/(\d{1,2})/$', my_view),
  286. )
  287. Here's the same thing, with ``my_view`` wrapped in ``cache_page``::
  288. from django.views.decorators.cache import cache_page
  289. urlpatterns = ('',
  290. (r'^foo/(\d{1,2})/$', cache_page(my_view, 60 * 15)),
  291. )
  292. If you take this approach, don't forget to import ``cache_page`` within your
  293. URLconf.
  294. Template fragment caching
  295. =========================
  296. .. versionadded:: 1.0
  297. If you're after even more control, you can also cache template fragments using
  298. the ``cache`` template tag. To give your template access to this tag, put
  299. ``{% load cache %}`` near the top of your template.
  300. The ``{% cache %}`` template tag caches the contents of the block for a given
  301. amount of time. It takes at least two arguments: the cache timeout, in seconds,
  302. and the name to give the cache fragment. For example:
  303. .. code-block:: html+django
  304. {% load cache %}
  305. {% cache 500 sidebar %}
  306. .. sidebar ..
  307. {% endcache %}
  308. Sometimes you might want to cache multiple copies of a fragment depending on
  309. some dynamic data that appears inside the fragment. For example, you might want a
  310. separate cached copy of the sidebar used in the previous example for every user
  311. of your site. Do this by passing additional arguments to the ``{% cache %}``
  312. template tag to uniquely identify the cache fragment:
  313. .. code-block:: html+django
  314. {% load cache %}
  315. {% cache 500 sidebar request.user.username %}
  316. .. sidebar for logged in user ..
  317. {% endcache %}
  318. It's perfectly fine to specify more than one argument to identify the fragment.
  319. Simply pass as many arguments to ``{% cache %}`` as you need.
  320. If :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will
  321. :ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template
  322. tag you could use one of the
  323. :ref:`translation-specific variables<template-translation-vars>` available in
  324. templates to archieve the same result:
  325. .. code-block:: html+django
  326. {% load i18n %}
  327. {% load cache %}
  328. {% get_current_language as LANGUAGE_CODE %}
  329. {% cache 600 welcome LANGUAGE_CODE %}
  330. {% trans "Welcome to example.com" %}
  331. {% endcache %}
  332. The cache timeout can be a template variable, as long as the template variable
  333. resolves to an integer value. For example, if the template variable
  334. ``my_timeout`` is set to the value ``600``, then the following two examples are
  335. equivalent:
  336. .. code-block:: html+django
  337. {% cache 600 sidebar %} ... {% endcache %}
  338. {% cache my_timeout sidebar %} ... {% endcache %}
  339. This feature is useful in avoiding repetition in templates. You can set the
  340. timeout in a variable, in one place, and just reuse that value.
  341. The low-level cache API
  342. =======================
  343. .. highlight:: python
  344. Sometimes, caching an entire rendered page doesn't gain you very much and is,
  345. in fact, inconvenient overkill.
  346. Perhaps, for instance, your site includes a view whose results depend on
  347. several expensive queries, the results of which change at different intervals.
  348. In this case, it would not be ideal to use the full-page caching that the
  349. per-site or per-view cache strategies offer, because you wouldn't want to
  350. cache the entire result (since some of the data changes often), but you'd still
  351. want to cache the results that rarely change.
  352. For cases like this, Django exposes a simple, low-level cache API. You can use
  353. this API to store objects in the cache with any level of granularity you like.
  354. You can cache any Python object that can be pickled safely: strings,
  355. dictionaries, lists of model objects, and so forth. (Most common Python objects
  356. can be pickled; refer to the Python documentation for more information about
  357. pickling.)
  358. The cache module, ``django.core.cache``, has a ``cache`` object that's
  359. automatically created from the ``CACHE_BACKEND`` setting::
  360. >>> from django.core.cache import cache
  361. The basic interface is ``set(key, value, timeout)`` and ``get(key)``::
  362. >>> cache.set('my_key', 'hello, world!', 30)
  363. >>> cache.get('my_key')
  364. 'hello, world!'
  365. The ``timeout`` argument is optional and defaults to the ``timeout``
  366. argument in the ``CACHE_BACKEND`` setting (explained above). It's the number of
  367. seconds the value should be stored in the cache.
  368. If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
  369. # Wait 30 seconds for 'my_key' to expire...
  370. >>> cache.get('my_key')
  371. None
  372. We advise against storing the literal value ``None`` in the cache, because you
  373. won't be able to distinguish between your stored ``None`` value and a cache
  374. miss signified by a return value of ``None``.
  375. ``cache.get()`` can take a ``default`` argument. This specifies which value to
  376. return if the object doesn't exist in the cache::
  377. >>> cache.get('my_key', 'has expired')
  378. 'has expired'
  379. .. versionadded:: 1.0
  380. To add a key only if it doesn't already exist, use the ``add()`` method.
  381. It takes the same parameters as ``set()``, but it will not attempt to
  382. update the cache if the key specified is already present::
  383. >>> cache.set('add_key', 'Initial value')
  384. >>> cache.add('add_key', 'New value')
  385. >>> cache.get('add_key')
  386. 'Initial value'
  387. If you need to know whether ``add()`` stored a value in the cache, you can
  388. check the return value. It will return ``True`` if the value was stored,
  389. ``False`` otherwise.
  390. There's also a ``get_many()`` interface that only hits the cache once.
  391. ``get_many()`` returns a dictionary with all the keys you asked for that
  392. actually exist in the cache (and haven't expired)::
  393. >>> cache.set('a', 1)
  394. >>> cache.set('b', 2)
  395. >>> cache.set('c', 3)
  396. >>> cache.get_many(['a', 'b', 'c'])
  397. {'a': 1, 'b': 2, 'c': 3}
  398. .. versionadded:: 1.2
  399. To set multiple values more efficiently, use ``set_many()`` to pass a dictionary
  400. of key-value pairs::
  401. >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})
  402. >>> cache.get_many(['a', 'b', 'c'])
  403. {'a': 1, 'b': 2, 'c': 3}
  404. Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.
  405. You can delete keys explicitly with ``delete()``. This is an easy way of
  406. clearing the cache for a particular object::
  407. >>> cache.delete('a')
  408. .. versionadded:: 1.2
  409. If you want to clear a bunch of keys at once, ``delete_many()`` can take a list
  410. of keys to be cleared::
  411. >>> cache.delete_many(['a', 'b', 'c'])
  412. .. versionadded:: 1.2
  413. Finally, if you want to delete all the keys in the cache, use
  414. ``cache.clear()``. Be careful with this; ``clear()`` will remove *everything*
  415. from the cache, not just the keys set by your application. ::
  416. >>> cache.clear()
  417. .. versionadded:: 1.1
  418. You can also increment or decrement a key that already exists using the
  419. ``incr()`` or ``decr()`` methods, respectively. By default, the existing cache
  420. value will incremented or decremented by 1. Other increment/decrement values
  421. can be specified by providing an argument to the increment/decrement call. A
  422. ValueError will be raised if you attempt to increment or decrement a
  423. nonexistent cache key.::
  424. >>> cache.set('num', 1)
  425. >>> cache.incr('num')
  426. 2
  427. >>> cache.incr('num', 10)
  428. 12
  429. >>> cache.decr('num')
  430. 11
  431. >>> cache.decr('num', 5)
  432. 6
  433. .. note::
  434. ``incr()``/``decr()`` methods are not guaranteed to be atomic. On those
  435. backends that support atomic increment/decrement (most notably, the
  436. memcached backend), increment and decrement operations will be atomic.
  437. However, if the backend doesn't natively provide an increment/decrement
  438. operation, it will be implemented using a two-step retrieve/update.
  439. Upstream caches
  440. ===============
  441. So far, this document has focused on caching your *own* data. But another type
  442. of caching is relevant to Web development, too: caching performed by "upstream"
  443. caches. These are systems that cache pages for users even before the request
  444. reaches your Web site.
  445. Here are a few examples of upstream caches:
  446. * Your ISP may cache certain pages, so if you requested a page from
  447. http://example.com/, your ISP would send you the page without having to
  448. access example.com directly. The maintainers of example.com have no
  449. knowledge of this caching; the ISP sits between example.com and your Web
  450. browser, handling all of the caching transparently.
  451. * Your Django Web site may sit behind a *proxy cache*, such as Squid Web
  452. Proxy Cache (http://www.squid-cache.org/), that caches pages for
  453. performance. In this case, each request first would be handled by the
  454. proxy, and it would be passed to your application only if needed.
  455. * Your Web browser caches pages, too. If a Web page sends out the
  456. appropriate headers, your browser will use the local cached copy for
  457. subsequent requests to that page, without even contacting the Web page
  458. again to see whether it has changed.
  459. Upstream caching is a nice efficiency boost, but there's a danger to it:
  460. Many Web pages' contents differ based on authentication and a host of other
  461. variables, and cache systems that blindly save pages based purely on URLs could
  462. expose incorrect or sensitive data to subsequent visitors to those pages.
  463. For example, say you operate a Web e-mail system, and the contents of the
  464. "inbox" page obviously depend on which user is logged in. If an ISP blindly
  465. cached your site, then the first user who logged in through that ISP would have
  466. his user-specific inbox page cached for subsequent visitors to the site. That's
  467. not cool.
  468. Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
  469. exist to instruct upstream caches to differ their cache contents depending on
  470. designated variables, and to tell caching mechanisms not to cache particular
  471. pages. We'll look at some of these headers in the sections that follow.
  472. Using Vary headers
  473. ==================
  474. The ``Vary`` header defines which request headers a cache
  475. mechanism should take into account when building its cache key. For example, if
  476. the contents of a Web page depend on a user's language preference, the page is
  477. said to "vary on language."
  478. By default, Django's cache system creates its cache keys using the requested
  479. path (e.g., ``"/stories/2005/jun/23/bank_robbed/"``). This means every request
  480. to that URL will use the same cached version, regardless of user-agent
  481. differences such as cookies or language preferences. However, if this page
  482. produces different content based on some difference in request headers -- such
  483. as a cookie, or a language, or a user-agent -- you'll need to use the ``Vary``
  484. header to tell caching mechanisms that the page output depends on those things.
  485. To do this in Django, use the convenient ``vary_on_headers`` view decorator,
  486. like so::
  487. from django.views.decorators.vary import vary_on_headers
  488. @vary_on_headers('User-Agent')
  489. def my_view(request):
  490. # ...
  491. In this case, a caching mechanism (such as Django's own cache middleware) will
  492. cache a separate version of the page for each unique user-agent.
  493. The advantage to using the ``vary_on_headers`` decorator rather than manually
  494. setting the ``Vary`` header (using something like
  495. ``response['Vary'] = 'user-agent'``) is that the decorator *adds* to the
  496. ``Vary`` header (which may already exist), rather than setting it from scratch
  497. and potentially overriding anything that was already in there.
  498. You can pass multiple headers to ``vary_on_headers()``::
  499. @vary_on_headers('User-Agent', 'Cookie')
  500. def my_view(request):
  501. # ...
  502. This tells upstream caches to vary on *both*, which means each combination of
  503. user-agent and cookie will get its own cache value. For example, a request with
  504. the user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered
  505. different from a request with the user-agent ``Mozilla`` and the cookie value
  506. ``foo=ham``.
  507. Because varying on cookie is so common, there's a ``vary_on_cookie``
  508. decorator. These two views are equivalent::
  509. @vary_on_cookie
  510. def my_view(request):
  511. # ...
  512. @vary_on_headers('Cookie')
  513. def my_view(request):
  514. # ...
  515. The headers you pass to ``vary_on_headers`` are not case sensitive;
  516. ``"User-Agent"`` is the same thing as ``"user-agent"``.
  517. You can also use a helper function, ``django.utils.cache.patch_vary_headers``,
  518. directly. This function sets, or adds to, the ``Vary header``. For example::
  519. from django.utils.cache import patch_vary_headers
  520. def my_view(request):
  521. # ...
  522. response = render_to_response('template_name', context)
  523. patch_vary_headers(response, ['Cookie'])
  524. return response
  525. ``patch_vary_headers`` takes an ``HttpResponse`` instance as its first argument
  526. and a list/tuple of case-insensitive header names as its second argument.
  527. For more on Vary headers, see the `official Vary spec`_.
  528. .. _`official Vary spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
  529. Controlling cache: Using other headers
  530. ======================================
  531. Other problems with caching are the privacy of data and the question of where
  532. data should be stored in a cascade of caches.
  533. A user usually faces two kinds of caches: his or her own browser cache (a
  534. private cache) and his or her provider's cache (a public cache). A public cache
  535. is used by multiple users and controlled by someone else. This poses problems
  536. with sensitive data--you don't want, say, your bank account number stored in a
  537. public cache. So Web applications need a way to tell caches which data is
  538. private and which is public.
  539. The solution is to indicate a page's cache should be "private." To do this in
  540. Django, use the ``cache_control`` view decorator. Example::
  541. from django.views.decorators.cache import cache_control
  542. @cache_control(private=True)
  543. def my_view(request):
  544. # ...
  545. This decorator takes care of sending out the appropriate HTTP header behind the
  546. scenes.
  547. There are a few other ways to control cache parameters. For example, HTTP
  548. allows applications to do the following:
  549. * Define the maximum time a page should be cached.
  550. * Specify whether a cache should always check for newer versions, only
  551. delivering the cached content when there are no changes. (Some caches
  552. might deliver cached content even if the server page changed, simply
  553. because the cache copy isn't yet expired.)
  554. In Django, use the ``cache_control`` view decorator to specify these cache
  555. parameters. In this example, ``cache_control`` tells caches to revalidate the
  556. cache on every access and to store cached versions for, at most, 3,600 seconds::
  557. from django.views.decorators.cache import cache_control
  558. @cache_control(must_revalidate=True, max_age=3600)
  559. def my_view(request):
  560. # ...
  561. Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
  562. Here's a full list:
  563. * ``public=True``
  564. * ``private=True``
  565. * ``no_cache=True``
  566. * ``no_transform=True``
  567. * ``must_revalidate=True``
  568. * ``proxy_revalidate=True``
  569. * ``max_age=num_seconds``
  570. * ``s_maxage=num_seconds``
  571. For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
  572. (Note that the caching middleware already sets the cache header's max-age with
  573. the value of the ``CACHE_MIDDLEWARE_SETTINGS`` setting. If you use a custom
  574. ``max_age`` in a ``cache_control`` decorator, the decorator will take
  575. precedence, and the header values will be merged correctly.)
  576. If you want to use headers to disable caching altogether,
  577. ``django.views.decorators.cache.never_cache`` is a view decorator that adds
  578. headers to ensure the response won't be cached by browsers or other caches.
  579. Example::
  580. from django.views.decorators.cache import never_cache
  581. @never_cache
  582. def myview(request):
  583. # ...
  584. .. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  585. Other optimizations
  586. ===================
  587. Django comes with a few other pieces of middleware that can help optimize your
  588. site's performance:
  589. * ``django.middleware.http.ConditionalGetMiddleware`` adds support for
  590. modern browsers to conditionally GET responses based on the ``ETag``
  591. and ``Last-Modified`` headers.
  592. * ``django.middleware.gzip.GZipMiddleware`` compresses responses for all
  593. moderns browsers, saving bandwidth and transfer time.
  594. Order of MIDDLEWARE_CLASSES
  595. ===========================
  596. If you use caching middleware, it's important to put each half in the right
  597. place within the ``MIDDLEWARE_CLASSES`` setting. That's because the cache
  598. middleware needs to know which headers by which to vary the cache storage.
  599. Middleware always adds something to the ``Vary`` response header when it can.
  600. ``UpdateCacheMiddleware`` runs during the response phase, where middleware is
  601. run in reverse order, so an item at the top of the list runs *last* during the
  602. response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
  603. appears *before* any other middleware that might add something to the ``Vary``
  604. header. The following middleware modules do so:
  605. * ``SessionMiddleware`` adds ``Cookie``
  606. * ``GZipMiddleware`` adds ``Accept-Encoding``
  607. * ``LocaleMiddleware`` adds ``Accept-Language``
  608. ``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
  609. where middleware is applied first-to-last, so an item at the top of the list
  610. runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
  611. needs to run after other middleware updates the ``Vary`` header, so
  612. ``FetchFromCacheMiddleware`` must be *after* any item that does so.