cache.txt 32 KB

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