cache.txt 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. ========================
  2. Django's cache framework
  3. ========================
  4. A fundamental trade-off in dynamic Web sites is, well, they're dynamic. Each
  5. time a user requests a page, the Web server makes all sorts of calculations --
  6. from database queries to template rendering to business logic -- to create the
  7. page that your site's visitor sees. This is a lot more expensive, from a
  8. processing-overhead perspective, than your standard
  9. read-a-file-off-the-filesystem server arrangement.
  10. For most Web applications, this overhead isn't a big deal. Most Web
  11. applications aren't washingtonpost.com or slashdot.org; they're simply small-
  12. to medium-sized sites with so-so traffic. But for medium- to high-traffic
  13. sites, it's essential to cut as much overhead as possible.
  14. That's where caching comes in.
  15. To cache something is to save the result of an expensive calculation so that
  16. you don't have to perform the calculation next time. Here's some pseudocode
  17. explaining how this would work for a dynamically generated Web page::
  18. given a URL, try finding that page in the cache
  19. if the page is in the cache:
  20. return the cached page
  21. else:
  22. generate the page
  23. save the generated page in the cache (for next time)
  24. return the generated page
  25. Django comes with a robust cache system that lets you save dynamic pages so
  26. they don't have to be calculated for each request. For convenience, Django
  27. offers different levels of cache granularity: You can cache the output of
  28. specific views, you can cache only the pieces that are difficult to produce,
  29. or you can cache your entire site.
  30. Django also works well with "upstream" caches, such as `Squid
  31. <http://www.squid-cache.org>`_ and browser-based caches. These are the types of
  32. caches that you don't directly control but to which you can provide hints (via
  33. HTTP headers) about which parts of your site should be cached, and how.
  34. Setting up the cache
  35. ====================
  36. The cache system requires a small amount of setup. Namely, you have to tell it
  37. where your cached data should live -- whether in a database, on the filesystem
  38. or directly in memory. This is an important decision that affects your cache's
  39. performance; yes, some cache types are faster than others.
  40. Your cache preference goes in the :setting:`CACHES` setting in your
  41. settings file. Here's an explanation of all available values for
  42. :setting:`CACHES`.
  43. .. versionchanged:: 1.3
  44. The settings used to configure caching changed in Django 1.3. In
  45. Django 1.2 and earlier, you used a single string-based
  46. :setting:`CACHE_BACKEND` setting to configure caches. This has
  47. been replaced with the new dictionary-based :setting:`CACHES`
  48. setting.
  49. Memcached
  50. ---------
  51. By far the fastest, most efficient type of cache available to Django, Memcached
  52. is an entirely memory-based cache framework originally developed to handle high
  53. loads at LiveJournal.com and subsequently open-sourced by Danga Interactive.
  54. It's used by sites such as Facebook and Wikipedia to reduce database access and
  55. dramatically increase site performance.
  56. Memcached is available for free at http://memcached.org/. It runs as a
  57. daemon and is allotted a specified amount of RAM. All it does is provide a
  58. fast interface for adding, retrieving and deleting arbitrary data in the cache.
  59. All data is stored directly in memory, so there's no overhead of database or
  60. filesystem usage.
  61. After installing Memcached itself, you'll need to install a memcached
  62. binding. There are several python memcached bindings available; the
  63. two most common are `python-memcached`_ and `pylibmc`_.
  64. .. _`python-memcached`: ftp://ftp.tummy.com/pub/python-memcached/
  65. .. _`pylibmc`: http://sendapatch.se/projects/pylibmc/
  66. .. versionchanged:: 1.2
  67. In Django 1.0 and 1.1, you could also use ``cmemcache`` as a binding.
  68. However, support for this library was deprecated in 1.2 due to
  69. a lack of maintenance on the ``cmemcache`` library itself. Support for
  70. ``cmemcache`` will be removed completely in Django 1.4.
  71. .. versionchanged:: 1.3
  72. Support for ``pylibmc`` was added.
  73. To use Memcached with Django:
  74. * Set :setting:`BACKEND <CACHES-BACKEND>` to
  75. ``django.core.cache.backends.memcached.MemcachedCache`` or
  76. ``django.core.cache.backends.memcached.PyLibMCCache`` (depending
  77. on your chosen memcached binding)
  78. * Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,
  79. where ``ip`` is the IP address of the Memcached daemon and
  80. ``port`` is the port on which Memcached is running.
  81. In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
  82. the ``python-memcached`` binding::
  83. CACHES = {
  84. 'default': {
  85. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  86. 'LOCATION': '127.0.0.1:11211',
  87. }
  88. }
  89. One excellent feature of Memcached is its ability to share cache over multiple
  90. servers. This means you can run Memcached daemons on multiple machines, and the
  91. program will treat the group of machines as a *single* cache, without the need
  92. to duplicate cache values on each machine. To take advantage of this feature,
  93. include all server addresses in :setting:`BACKEND <CACHES-BACKEND>`, either
  94. separated by semicolons or as a list.
  95. In this example, the cache is shared over Memcached instances running on IP
  96. address 172.19.26.240 and 172.19.26.242, both on port 11211::
  97. CACHES = {
  98. 'default': {
  99. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  100. 'LOCATION': [
  101. '172.19.26.240:11211',
  102. '172.19.26.242:11211',
  103. ]
  104. }
  105. }
  106. In the following example, the cache is shared over Memcached instances running
  107. on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
  108. 172.19.26.244 (port 11213)::
  109. CACHES = {
  110. 'default': {
  111. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  112. 'LOCATION': [
  113. '172.19.26.240:11211',
  114. '172.19.26.242:11211',
  115. '172.19.26.244:11213',
  116. ]
  117. }
  118. }
  119. A final point about Memcached is that memory-based caching has one
  120. disadvantage: Because the cached data is stored in memory, the data will be
  121. lost if your server crashes. Clearly, memory isn't intended for permanent data
  122. storage, so don't rely on memory-based caching as your only data storage.
  123. Without a doubt, *none* of the Django caching backends should be used for
  124. permanent storage -- they're all intended to be solutions for caching, not
  125. storage -- but we point this out here because memory-based caching is
  126. particularly temporary.
  127. Database caching
  128. ----------------
  129. To use a database table as your cache backend, first create a cache table in
  130. your database by running this command::
  131. python manage.py createcachetable [cache_table_name]
  132. ...where ``[cache_table_name]`` is the name of the database table to create.
  133. (This name can be whatever you want, as long as it's a valid table name that's
  134. not already being used in your database.) This command creates a single table
  135. in your database that is in the proper format that Django's database-cache
  136. system expects.
  137. Once you've created that database table, set your
  138. :setting:`BACKEND <CACHES-BACKEND>` setting to
  139. ``"django.core.cache.backends.db.DatabaseCache"``, and
  140. :setting:`LOCATION <CACHES-LOCATION>` to ``tablename`` -- the name of the
  141. database table. In this example, the cache table's name is ``my_cache_table``::
  142. CACHES = {
  143. 'default': {
  144. 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
  145. 'LOCATION': 'my_cache_table',
  146. }
  147. }
  148. The database caching backend uses the same database as specified in your
  149. settings file. You can't use a different database backend for your cache table.
  150. Database caching works best if you've got a fast, well-indexed database server.
  151. Database caching and multiple databases
  152. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  153. If you use database caching with multiple databases, you'll also need
  154. to set up routing instructions for your database cache table. For the
  155. purposes of routing, the database cache table appears as a model named
  156. ``CacheEntry``, in an application named ``django_cache``. This model
  157. won't appear in the models cache, but the model details can be used
  158. for routing purposes.
  159. For example, the following router would direct all cache read
  160. operations to ``cache_slave``, and all write operations to
  161. ``cache_master``. The cache table will only be synchronized onto
  162. ``cache_master``::
  163. class CacheRouter(object):
  164. """A router to control all database cache operations"""
  165. def db_for_read(self, model, **hints):
  166. "All cache read operations go to the slave"
  167. if model._meta.app_label in ('django_cache',):
  168. return 'cache_slave'
  169. return None
  170. def db_for_write(self, model, **hints):
  171. "All cache write operations go to master"
  172. if model._meta.app_label in ('django_cache',):
  173. return 'cache_master'
  174. return None
  175. def allow_syncdb(self, db, model):
  176. "Only synchronize the cache model on master"
  177. if model._meta.app_label in ('django_cache',):
  178. return db == 'cache_master'
  179. return None
  180. If you don't specify routing directions for the database cache model,
  181. the cache backend will use the ``default`` database.
  182. Of course, if you don't use the database cache backend, you don't need
  183. to worry about providing routing instructions for the database cache
  184. model.
  185. Filesystem caching
  186. ------------------
  187. To store cached items on a filesystem, use
  188. ``"django.core.cache.backends.filebased.FileBasedCache"`` for
  189. :setting:`BACKEND <CACHES-BACKEND>`. For example, to store cached data in
  190. ``/var/tmp/django_cache``, use this setting::
  191. CACHES = {
  192. 'default': {
  193. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  194. 'LOCATION': '/var/tmp/django_cache',
  195. }
  196. }
  197. If you're on Windows, put the drive letter at the beginning of the path,
  198. like this::
  199. CACHES = {
  200. 'default': {
  201. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  202. 'LOCATION': 'c:/foo/bar',
  203. }
  204. }
  205. The directory path should be absolute -- that is, it should start at the root
  206. of your filesystem. It doesn't matter whether you put a slash at the end of the
  207. setting.
  208. Make sure the directory pointed-to by this setting exists and is readable and
  209. writable by the system user under which your Web server runs. Continuing the
  210. above example, if your server runs as the user ``apache``, make sure the
  211. directory ``/var/tmp/django_cache`` exists and is readable and writable by the
  212. user ``apache``.
  213. Each cache value will be stored as a separate file whose contents are the
  214. cache data saved in a serialized ("pickled") format, using Python's ``pickle``
  215. module. Each file's name is the cache key, escaped for safe filesystem use.
  216. Local-memory caching
  217. --------------------
  218. If you want the speed advantages of in-memory caching but don't have the
  219. capability of running Memcached, consider the local-memory cache backend. This
  220. cache is multi-process and thread-safe. To use it, set
  221. :setting:`BACKEND <CACHES-BACKEND>` to
  222. ``"django.core.cache.backends.locmem.LocMemCache"``. For example::
  223. CACHES = {
  224. 'default': {
  225. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  226. 'LOCATION': 'unique-snowflake'
  227. }
  228. }
  229. The cache :setting:`LOCATION <CACHES-LOCATION>` is used to identify individual
  230. memory stores. If you only have one locmem cache, you can omit the
  231. :setting:`LOCATION <CACHES-LOCATION>`; however, if you have more that one local
  232. memory cache, you will need to assign a name to at least one of them in
  233. order to keep them separate.
  234. Note that each process will have its own private cache instance, which means no
  235. cross-process caching is possible. This obviously also means the local memory
  236. cache isn't particularly memory-efficient, so it's probably not a good choice
  237. for production environments. It's nice for development.
  238. Dummy caching (for development)
  239. -------------------------------
  240. Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
  241. just implements the cache interface without doing anything.
  242. This is useful if you have a production site that uses heavy-duty caching in
  243. various places but a development/test environment where you don't want to cache
  244. and don't want to have to change your code to special-case the latter. To
  245. activate dummy caching, set :setting:`BACKEND <CACHES-BACKEND>` like so::
  246. CACHES = {
  247. 'default': {
  248. 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
  249. }
  250. }
  251. Using a custom cache backend
  252. ----------------------------
  253. While Django includes support for a number of cache backends out-of-the-box,
  254. sometimes you might want to use a customized cache backend. To use an external
  255. cache backend with Django, use the Python import path as the
  256. :setting:`BACKEND <CACHES-BACKEND>` of the :setting:`CACHES` setting, like so::
  257. CACHES = {
  258. 'default': {
  259. 'BACKEND': 'path.to.backend',
  260. }
  261. }
  262. If you're building your own backend, you can use the standard cache backends
  263. as reference implementations. You'll find the code in the
  264. ``django/core/cache/backends/`` directory of the Django source.
  265. Note: Without a really compelling reason, such as a host that doesn't support
  266. them, you should stick to the cache backends included with Django. They've
  267. been well-tested and are easy to use.
  268. Cache arguments
  269. ---------------
  270. In addition to the defining the engine and name of the each cache
  271. backend, each cache backend can be given additional arguments to
  272. control caching behavior. These arguments are provided as additional
  273. keys in the :setting:`CACHES` setting. Valid arguments are as follows:
  274. * :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in
  275. seconds, to use for the cache. This argument defaults to 300
  276. seconds (5 minutes).
  277. * :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be
  278. passed to cache backend. The list options understood by each
  279. backend vary with each backend.
  280. Cache backends that implement their own culling strategy (i.e.,
  281. the ``locmem``, ``filesystem`` and ``database`` backends) will
  282. honor the following options:
  283. * ``MAX_ENTRIES``: the maximum number of entries allowed in
  284. the cache before old values are deleted. This argument
  285. defaults to ``300``.
  286. * ``CULL_FREQUENCY``: The fraction of entries that are culled
  287. when ``MAX_ENTRIES`` is reached. The actual ratio is
  288. ``1/CULL_FREQUENCY``, so set ``CULL_FREQUENCY``: to ``2`` to
  289. cull half of the entries when ``MAX_ENTRIES`` is reached.
  290. A value of ``0`` for ``CULL_FREQUENCY`` means that the
  291. entire cache will be dumped when ``MAX_ENTRIES`` is reached.
  292. This makes culling *much* faster at the expense of more
  293. cache misses.
  294. Cache backends backed by a third-party library will pass their
  295. options directly to the underlying cache library. As a result,
  296. the list of valid options depends on the library in use.
  297. * :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be
  298. automatically included (prepended by default) to all cache keys
  299. used by the Django server.
  300. See the :ref:`cache documentation <cache_key_prefixing>` for
  301. more information.
  302. * :setting:`VERSION <CACHES-VERSION>`: The default version number
  303. for cache keys generated by the Django server.
  304. See the :ref:`cache documentation <cache_versioning>` for more
  305. information.
  306. * :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`
  307. A string containing a dotted path to a function that defines how
  308. to compose a prefix, version and key into a final cache key.
  309. See the :ref:`cache documentation <cache_key_transformation>`
  310. for more information.
  311. In this example, a filesystem backend is being configured with a timeout
  312. of 60 seconds, and a maximum capacity of 1000 items::
  313. CACHES = {
  314. 'default': {
  315. 'BACKEND': 'django.core.cache.backends.filebased.FileCache',
  316. 'LOCATION': '127.0.0.1:11211',
  317. 'TIMEOUT': 60,
  318. 'OPTIONS': {
  319. 'MAX_ENTRIES': 1000
  320. }
  321. }
  322. }
  323. Invalid arguments are silently ignored, as are invalid values of known
  324. arguments.
  325. The per-site cache
  326. ==================
  327. Once the cache is set up, the simplest way to use caching is to cache your
  328. entire site. You'll need to add
  329. ``'django.middleware.cache.UpdateCacheMiddleware'`` and
  330. ``'django.middleware.cache.FetchFromCacheMiddleware'`` to your
  331. ``MIDDLEWARE_CLASSES`` setting, as in this example::
  332. MIDDLEWARE_CLASSES = (
  333. 'django.middleware.cache.UpdateCacheMiddleware',
  334. 'django.middleware.common.CommonMiddleware',
  335. 'django.middleware.cache.FetchFromCacheMiddleware',
  336. )
  337. .. note::
  338. No, that's not a typo: the "update" middleware must be first in the list,
  339. and the "fetch" middleware must be last. The details are a bit obscure, but
  340. see `Order of MIDDLEWARE_CLASSES`_ below if you'd like the full story.
  341. Then, add the following required settings to your Django settings file:
  342. * :setting:`CACHE_MIDDLEWARE_ALIAS` -- The cache alias to use for storage.
  343. * :setting:`CACHE_MIDDLEWARE_SECONDS` -- The number of seconds each page should
  344. be cached.
  345. * :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` -- If the cache is shared across
  346. multiple sites using the same Django installation, set this to the name of
  347. the site, or some other string that is unique to this Django instance, to
  348. prevent key collisions. Use an empty string if you don't care.
  349. The cache middleware caches every page that doesn't have GET or POST
  350. parameters. Optionally, if the :setting:`CACHE_MIDDLEWARE_ANONYMOUS_ONLY`
  351. setting is ``True``, only anonymous requests (i.e., not those made by a
  352. logged-in user) will be cached. This is a simple and effective way of disabling
  353. caching for any user-specific pages (include Django's admin interface). Note
  354. that if you use :setting:`CACHE_MIDDLEWARE_ANONYMOUS_ONLY`, you should make
  355. sure you've activated ``AuthenticationMiddleware``. The cache middleware
  356. expects that a HEAD request is answered with the same response headers as
  357. the corresponding GET request; in which case it can return a cached GET
  358. response for HEAD request.
  359. Additionally, the cache middleware automatically sets a few headers in each
  360. :class:`~django.http.HttpResponse`:
  361. * Sets the ``Last-Modified`` header to the current date/time when a fresh
  362. (uncached) version of the page is requested.
  363. * Sets the ``Expires`` header to the current date/time plus the defined
  364. :setting:`CACHE_MIDDLEWARE_SECONDS`.
  365. * Sets the ``Cache-Control`` header to give a max age for the page --
  366. again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.
  367. See :doc:`/topics/http/middleware` for more on middleware.
  368. If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
  369. its ``Cache-Control`` header) then the page will be cached until the expiry
  370. time, rather than :setting:`CACHE_MIDDLEWARE_SECONDS`. Using the decorators in
  371. ``django.views.decorators.cache`` you can easily set a view's expiry time
  372. (using the ``cache_control`` decorator) or disable caching for a view (using
  373. the ``never_cache`` decorator). See the `using other headers`__ section for
  374. more on these decorators.
  375. .. _i18n-cache-key:
  376. .. versionadded:: 1.2
  377. If :setting:`USE_I18N` is set to ``True`` then the generated cache key will
  378. include the name of the active :term:`language<language code>`.
  379. This allows you to easily cache multilingual sites without having to create
  380. the cache key yourself.
  381. See :doc:`/topics/i18n/deployment` for more on how Django discovers the active
  382. language.
  383. __ `Controlling cache: Using other headers`_
  384. The per-view cache
  385. ==================
  386. .. function ``django.views.decorators.cache.cache_page``
  387. A more granular way to use the caching framework is by caching the output of
  388. individual views. ``django.views.decorators.cache`` defines a ``cache_page``
  389. decorator that will automatically cache the view's response for you. It's easy
  390. to use::
  391. from django.views.decorators.cache import cache_page
  392. @cache_page(60 * 15)
  393. def my_view(request):
  394. ...
  395. ``cache_page`` takes a single argument: the cache timeout, in seconds. In the
  396. above example, the result of the ``my_view()`` view will be cached for 15
  397. minutes. (Note that we've written it as ``60 * 15`` for the purpose of
  398. readability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes
  399. multiplied by 60 seconds per minute.)
  400. The per-view cache, like the per-site cache, is keyed off of the URL. If
  401. multiple URLs point at the same view, each URL will be cached separately.
  402. Continuing the ``my_view`` example, if your URLconf looks like this::
  403. urlpatterns = ('',
  404. (r'^foo/(\d{1,2})/$', my_view),
  405. )
  406. then requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as
  407. you may expect. But once a particular URL (e.g., ``/foo/23/``) has been
  408. requested, subsequent requests to that URL will use the cache.
  409. ``cache_page`` can also take an optional keyword argument, ``cache``,
  410. which directs the decorator to use a specific cache alias when caching view
  411. results. By default, the ``default`` alias will be used, but you can specify
  412. any cache alias you want::
  413. @cache_page(60 * 15, cache="special_cache")
  414. def my_view(request):
  415. ...
  416. You can also override the cache prefix on a per-view basis. ``cache_page``
  417. takes an optional keyword argument, ``key_prefix``,
  418. which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`
  419. setting for the middleware. It can be used like this::
  420. @cache_page(60 * 15, key_prefix="site1")
  421. def my_view(request):
  422. ...
  423. The two settings can also be combined. If you specify a ``cache`` *and*
  424. a ``key_prefix``, you will get all the settings of the requested cache
  425. alias, but with the key_prefix overridden.
  426. Specifying per-view cache in the URLconf
  427. ----------------------------------------
  428. The examples in the previous section have hard-coded the fact that the view is
  429. cached, because ``cache_page`` alters the ``my_view`` function in place. This
  430. approach couples your view to the cache system, which is not ideal for several
  431. reasons. For instance, you might want to reuse the view functions on another,
  432. cache-less site, or you might want to distribute the views to people who might
  433. want to use them without being cached. The solution to these problems is to
  434. specify the per-view cache in the URLconf rather than next to the view functions
  435. themselves.
  436. Doing so is easy: simply wrap the view function with ``cache_page`` when you
  437. refer to it in the URLconf. Here's the old URLconf from earlier::
  438. urlpatterns = ('',
  439. (r'^foo/(\d{1,2})/$', my_view),
  440. )
  441. Here's the same thing, with ``my_view`` wrapped in ``cache_page``::
  442. from django.views.decorators.cache import cache_page
  443. urlpatterns = ('',
  444. (r'^foo/(\d{1,2})/$', cache_page(my_view, 60 * 15)),
  445. )
  446. If you take this approach, don't forget to import ``cache_page`` within your
  447. URLconf.
  448. Template fragment caching
  449. =========================
  450. If you're after even more control, you can also cache template fragments using
  451. the ``cache`` template tag. To give your template access to this tag, put
  452. ``{% load cache %}`` near the top of your template.
  453. The ``{% cache %}`` template tag caches the contents of the block for a given
  454. amount of time. It takes at least two arguments: the cache timeout, in seconds,
  455. and the name to give the cache fragment. For example:
  456. .. code-block:: html+django
  457. {% load cache %}
  458. {% cache 500 sidebar %}
  459. .. sidebar ..
  460. {% endcache %}
  461. Sometimes you might want to cache multiple copies of a fragment depending on
  462. some dynamic data that appears inside the fragment. For example, you might want a
  463. separate cached copy of the sidebar used in the previous example for every user
  464. of your site. Do this by passing additional arguments to the ``{% cache %}``
  465. template tag to uniquely identify the cache fragment:
  466. .. code-block:: html+django
  467. {% load cache %}
  468. {% cache 500 sidebar request.user.username %}
  469. .. sidebar for logged in user ..
  470. {% endcache %}
  471. It's perfectly fine to specify more than one argument to identify the fragment.
  472. Simply pass as many arguments to ``{% cache %}`` as you need.
  473. If :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will
  474. :ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template
  475. tag you could use one of the
  476. :ref:`translation-specific variables<template-translation-vars>` available in
  477. templates to archieve the same result:
  478. .. code-block:: html+django
  479. {% load i18n %}
  480. {% load cache %}
  481. {% get_current_language as LANGUAGE_CODE %}
  482. {% cache 600 welcome LANGUAGE_CODE %}
  483. {% trans "Welcome to example.com" %}
  484. {% endcache %}
  485. The cache timeout can be a template variable, as long as the template variable
  486. resolves to an integer value. For example, if the template variable
  487. ``my_timeout`` is set to the value ``600``, then the following two examples are
  488. equivalent:
  489. .. code-block:: html+django
  490. {% cache 600 sidebar %} ... {% endcache %}
  491. {% cache my_timeout sidebar %} ... {% endcache %}
  492. This feature is useful in avoiding repetition in templates. You can set the
  493. timeout in a variable, in one place, and just reuse that value.
  494. The low-level cache API
  495. =======================
  496. .. highlight:: python
  497. Sometimes, caching an entire rendered page doesn't gain you very much and is,
  498. in fact, inconvenient overkill.
  499. Perhaps, for instance, your site includes a view whose results depend on
  500. several expensive queries, the results of which change at different intervals.
  501. In this case, it would not be ideal to use the full-page caching that the
  502. per-site or per-view cache strategies offer, because you wouldn't want to
  503. cache the entire result (since some of the data changes often), but you'd still
  504. want to cache the results that rarely change.
  505. For cases like this, Django exposes a simple, low-level cache API. You can use
  506. this API to store objects in the cache with any level of granularity you like.
  507. You can cache any Python object that can be pickled safely: strings,
  508. dictionaries, lists of model objects, and so forth. (Most common Python objects
  509. can be pickled; refer to the Python documentation for more information about
  510. pickling.)
  511. The cache module, ``django.core.cache``, has a ``cache`` object that's
  512. automatically created from the ``'default'`` entry in the :setting:`CACHES`
  513. setting::
  514. >>> from django.core.cache import cache
  515. The basic interface is ``set(key, value, timeout)`` and ``get(key)``::
  516. >>> cache.set('my_key', 'hello, world!', 30)
  517. >>> cache.get('my_key')
  518. 'hello, world!'
  519. The ``timeout`` argument is optional and defaults to the ``timeout``
  520. argument of the ``'default'`` backend in :setting:`CACHES` setting
  521. (explained above). It's the number of seconds the value should be stored
  522. in the cache.
  523. If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
  524. # Wait 30 seconds for 'my_key' to expire...
  525. >>> cache.get('my_key')
  526. None
  527. We advise against storing the literal value ``None`` in the cache, because you
  528. won't be able to distinguish between your stored ``None`` value and a cache
  529. miss signified by a return value of ``None``.
  530. ``cache.get()`` can take a ``default`` argument. This specifies which value to
  531. return if the object doesn't exist in the cache::
  532. >>> cache.get('my_key', 'has expired')
  533. 'has expired'
  534. To add a key only if it doesn't already exist, use the ``add()`` method.
  535. It takes the same parameters as ``set()``, but it will not attempt to
  536. update the cache if the key specified is already present::
  537. >>> cache.set('add_key', 'Initial value')
  538. >>> cache.add('add_key', 'New value')
  539. >>> cache.get('add_key')
  540. 'Initial value'
  541. If you need to know whether ``add()`` stored a value in the cache, you can
  542. check the return value. It will return ``True`` if the value was stored,
  543. ``False`` otherwise.
  544. There's also a ``get_many()`` interface that only hits the cache once.
  545. ``get_many()`` returns a dictionary with all the keys you asked for that
  546. actually exist in the cache (and haven't expired)::
  547. >>> cache.set('a', 1)
  548. >>> cache.set('b', 2)
  549. >>> cache.set('c', 3)
  550. >>> cache.get_many(['a', 'b', 'c'])
  551. {'a': 1, 'b': 2, 'c': 3}
  552. .. versionadded:: 1.2
  553. To set multiple values more efficiently, use ``set_many()`` to pass a dictionary
  554. of key-value pairs::
  555. >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})
  556. >>> cache.get_many(['a', 'b', 'c'])
  557. {'a': 1, 'b': 2, 'c': 3}
  558. Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.
  559. You can delete keys explicitly with ``delete()``. This is an easy way of
  560. clearing the cache for a particular object::
  561. >>> cache.delete('a')
  562. .. versionadded:: 1.2
  563. If you want to clear a bunch of keys at once, ``delete_many()`` can take a list
  564. of keys to be cleared::
  565. >>> cache.delete_many(['a', 'b', 'c'])
  566. .. versionadded:: 1.2
  567. Finally, if you want to delete all the keys in the cache, use
  568. ``cache.clear()``. Be careful with this; ``clear()`` will remove *everything*
  569. from the cache, not just the keys set by your application. ::
  570. >>> cache.clear()
  571. You can also increment or decrement a key that already exists using the
  572. ``incr()`` or ``decr()`` methods, respectively. By default, the existing cache
  573. value will incremented or decremented by 1. Other increment/decrement values
  574. can be specified by providing an argument to the increment/decrement call. A
  575. ValueError will be raised if you attempt to increment or decrement a
  576. nonexistent cache key.::
  577. >>> cache.set('num', 1)
  578. >>> cache.incr('num')
  579. 2
  580. >>> cache.incr('num', 10)
  581. 12
  582. >>> cache.decr('num')
  583. 11
  584. >>> cache.decr('num', 5)
  585. 6
  586. .. note::
  587. ``incr()``/``decr()`` methods are not guaranteed to be atomic. On those
  588. backends that support atomic increment/decrement (most notably, the
  589. memcached backend), increment and decrement operations will be atomic.
  590. However, if the backend doesn't natively provide an increment/decrement
  591. operation, it will be implemented using a two-step retrieve/update.
  592. .. _cache_key_prefixing:
  593. Cache key prefixing
  594. -------------------
  595. .. versionadded:: 1.3
  596. If you are sharing a cache instance between servers, or between your
  597. production and development environments, it's possible for data cached
  598. by one server to be used by another server. If the format of cached
  599. data is different between servers, this can lead to some very hard to
  600. diagnose problems.
  601. To prevent this, Django provides the ability to prefix all cache keys
  602. used by a server. When a particular cache key is saved or retrieved,
  603. Django will automatically prefix the cache key with the value of the
  604. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` cache setting.
  605. By ensuring each Django instance has a different
  606. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`, you can ensure that there will be no
  607. collisions in cache values.
  608. .. _cache_versioning:
  609. Cache versioning
  610. ----------------
  611. .. versionadded:: 1.3
  612. When you change running code that uses cached values, you may need to
  613. purge any existing cached values. The easiest way to do this is to
  614. flush the entire cache, but this can lead to the loss of cache values
  615. that are still valid and useful.
  616. Django provides a better way to target individual cache values.
  617. Django's cache framework has a system-wide version identifier,
  618. specified using the :setting:`VERSION <CACHES-VERSION>` cache setting.
  619. The value of this setting is automatically combined with the cache
  620. prefix and the user-provided cache key to obtain the final cache key.
  621. By default, any key request will automatically include the site
  622. default cache key version. However, the primitive cache functions all
  623. include a ``version`` argument, so you can specify a particular cache
  624. key version to set or get. For example::
  625. # Set version 2 of a cache key
  626. >>> cache.set('my_key', 'hello world!', version=2)
  627. # Get the default version (assuming version=1)
  628. >>> cache.get('my_key')
  629. None
  630. # Get version 2 of the same key
  631. >>> cache.get('my_key', version=2)
  632. 'hello world!'
  633. The version of a specific key can be incremented and decremented using
  634. the :func:`incr_version()` and :func:`decr_version()` methods. This
  635. enables specific keys to be bumped to a new version, leaving other
  636. keys unaffected. Continuing our previous example::
  637. # Increment the version of 'my_key'
  638. >>> cache.incr_version('my_key')
  639. # The default version still isn't available
  640. >>> cache.get('my_key')
  641. None
  642. # Version 2 isn't available, either
  643. >>> cache.get('my_key', version=2)
  644. None
  645. # But version 3 *is* availble
  646. >>> cache.get('my_key', version=3)
  647. 'hello world!'
  648. .. _cache_key_transformation:
  649. Cache key transformation
  650. ------------------------
  651. .. versionadded:: 1.3
  652. As described in the previous two sections, the cache key provided by a
  653. user is not used verbatim -- it is combined with the cache prefix and
  654. key version to provide a final cache key. By default, the three parts
  655. are joined using colons to produce a final string::
  656. def make_key(key, key_prefix, version):
  657. return ':'.join([key_prefix, str(version), smart_str(key)])
  658. If you want to combine the parts in different ways, or apply other
  659. processing to the final key (e.g., taking a hash digest of the key
  660. parts), you can provide a custom key function.
  661. The :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting
  662. specifies a dotted-path to a function matching the prototype of
  663. :func:`make_key()` above. If provided, this custom key function will
  664. be used instead of the default key combining function.
  665. Cache key warnings
  666. ------------------
  667. .. versionadded:: 1.3
  668. Memcached, the most commonly-used production cache backend, does not allow
  669. cache keys longer than 250 characters or containing whitespace or control
  670. characters, and using such keys will cause an exception. To encourage
  671. cache-portable code and minimize unpleasant surprises, the other built-in cache
  672. backends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``)
  673. if a key is used that would cause an error on memcached.
  674. If you are using a production backend that can accept a wider range of keys (a
  675. custom backend, or one of the non-memcached built-in backends), and want to use
  676. this wider range without warnings, you can silence ``CacheKeyWarning`` with
  677. this code in the ``management`` module of one of your
  678. :setting:`INSTALLED_APPS`::
  679. import warnings
  680. from django.core.cache import CacheKeyWarning
  681. warnings.simplefilter("ignore", CacheKeyWarning)
  682. If you want to instead provide custom key validation logic for one of the
  683. built-in backends, you can subclass it, override just the ``validate_key``
  684. method, and follow the instructions for `using a custom cache backend`_. For
  685. instance, to do this for the ``locmem`` backend, put this code in a module::
  686. from django.core.cache.backends.locmem import LocMemCache
  687. class CustomLocMemCache(LocMemCache):
  688. def validate_key(self, key):
  689. """Custom validation, raising exceptions or warnings as needed."""
  690. # ...
  691. ...and use the dotted Python path to this class in the
  692. :setting:`BACKEND <CACHES-BACKEND>` portion of your :setting:`CACHES` setting.
  693. Upstream caches
  694. ===============
  695. So far, this document has focused on caching your *own* data. But another type
  696. of caching is relevant to Web development, too: caching performed by "upstream"
  697. caches. These are systems that cache pages for users even before the request
  698. reaches your Web site.
  699. Here are a few examples of upstream caches:
  700. * Your ISP may cache certain pages, so if you requested a page from
  701. http://example.com/, your ISP would send you the page without having to
  702. access example.com directly. The maintainers of example.com have no
  703. knowledge of this caching; the ISP sits between example.com and your Web
  704. browser, handling all of the caching transparently.
  705. * Your Django Web site may sit behind a *proxy cache*, such as Squid Web
  706. Proxy Cache (http://www.squid-cache.org/), that caches pages for
  707. performance. In this case, each request first would be handled by the
  708. proxy, and it would be passed to your application only if needed.
  709. * Your Web browser caches pages, too. If a Web page sends out the
  710. appropriate headers, your browser will use the local cached copy for
  711. subsequent requests to that page, without even contacting the Web page
  712. again to see whether it has changed.
  713. Upstream caching is a nice efficiency boost, but there's a danger to it:
  714. Many Web pages' contents differ based on authentication and a host of other
  715. variables, and cache systems that blindly save pages based purely on URLs could
  716. expose incorrect or sensitive data to subsequent visitors to those pages.
  717. For example, say you operate a Web e-mail system, and the contents of the
  718. "inbox" page obviously depend on which user is logged in. If an ISP blindly
  719. cached your site, then the first user who logged in through that ISP would have
  720. his user-specific inbox page cached for subsequent visitors to the site. That's
  721. not cool.
  722. Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
  723. exist to instruct upstream caches to differ their cache contents depending on
  724. designated variables, and to tell caching mechanisms not to cache particular
  725. pages. We'll look at some of these headers in the sections that follow.
  726. .. _using-vary-headers:
  727. Using Vary headers
  728. ==================
  729. The ``Vary`` header defines which request headers a cache
  730. mechanism should take into account when building its cache key. For example, if
  731. the contents of a Web page depend on a user's language preference, the page is
  732. said to "vary on language."
  733. By default, Django's cache system creates its cache keys using the requested
  734. path (e.g., ``"/stories/2005/jun/23/bank_robbed/"``). This means every request
  735. to that URL will use the same cached version, regardless of user-agent
  736. differences such as cookies or language preferences. However, if this page
  737. produces different content based on some difference in request headers -- such
  738. as a cookie, or a language, or a user-agent -- you'll need to use the ``Vary``
  739. header to tell caching mechanisms that the page output depends on those things.
  740. To do this in Django, use the convenient ``vary_on_headers`` view decorator,
  741. like so::
  742. from django.views.decorators.vary import vary_on_headers
  743. @vary_on_headers('User-Agent')
  744. def my_view(request):
  745. # ...
  746. In this case, a caching mechanism (such as Django's own cache middleware) will
  747. cache a separate version of the page for each unique user-agent.
  748. The advantage to using the ``vary_on_headers`` decorator rather than manually
  749. setting the ``Vary`` header (using something like
  750. ``response['Vary'] = 'user-agent'``) is that the decorator *adds* to the
  751. ``Vary`` header (which may already exist), rather than setting it from scratch
  752. and potentially overriding anything that was already in there.
  753. You can pass multiple headers to ``vary_on_headers()``::
  754. @vary_on_headers('User-Agent', 'Cookie')
  755. def my_view(request):
  756. # ...
  757. This tells upstream caches to vary on *both*, which means each combination of
  758. user-agent and cookie will get its own cache value. For example, a request with
  759. the user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered
  760. different from a request with the user-agent ``Mozilla`` and the cookie value
  761. ``foo=ham``.
  762. Because varying on cookie is so common, there's a ``vary_on_cookie``
  763. decorator. These two views are equivalent::
  764. @vary_on_cookie
  765. def my_view(request):
  766. # ...
  767. @vary_on_headers('Cookie')
  768. def my_view(request):
  769. # ...
  770. The headers you pass to ``vary_on_headers`` are not case sensitive;
  771. ``"User-Agent"`` is the same thing as ``"user-agent"``.
  772. You can also use a helper function, ``django.utils.cache.patch_vary_headers``,
  773. directly. This function sets, or adds to, the ``Vary header``. For example::
  774. from django.utils.cache import patch_vary_headers
  775. def my_view(request):
  776. # ...
  777. response = render_to_response('template_name', context)
  778. patch_vary_headers(response, ['Cookie'])
  779. return response
  780. ``patch_vary_headers`` takes an :class:`~django.http.HttpResponse` instance as
  781. its first argument and a list/tuple of case-insensitive header names as its
  782. second argument.
  783. For more on Vary headers, see the `official Vary spec`_.
  784. .. _`official Vary spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
  785. Controlling cache: Using other headers
  786. ======================================
  787. Other problems with caching are the privacy of data and the question of where
  788. data should be stored in a cascade of caches.
  789. A user usually faces two kinds of caches: his or her own browser cache (a
  790. private cache) and his or her provider's cache (a public cache). A public cache
  791. is used by multiple users and controlled by someone else. This poses problems
  792. with sensitive data--you don't want, say, your bank account number stored in a
  793. public cache. So Web applications need a way to tell caches which data is
  794. private and which is public.
  795. The solution is to indicate a page's cache should be "private." To do this in
  796. Django, use the ``cache_control`` view decorator. Example::
  797. from django.views.decorators.cache import cache_control
  798. @cache_control(private=True)
  799. def my_view(request):
  800. # ...
  801. This decorator takes care of sending out the appropriate HTTP header behind the
  802. scenes.
  803. There are a few other ways to control cache parameters. For example, HTTP
  804. allows applications to do the following:
  805. * Define the maximum time a page should be cached.
  806. * Specify whether a cache should always check for newer versions, only
  807. delivering the cached content when there are no changes. (Some caches
  808. might deliver cached content even if the server page changed, simply
  809. because the cache copy isn't yet expired.)
  810. In Django, use the ``cache_control`` view decorator to specify these cache
  811. parameters. In this example, ``cache_control`` tells caches to revalidate the
  812. cache on every access and to store cached versions for, at most, 3,600 seconds::
  813. from django.views.decorators.cache import cache_control
  814. @cache_control(must_revalidate=True, max_age=3600)
  815. def my_view(request):
  816. # ...
  817. Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
  818. Here's a full list:
  819. * ``public=True``
  820. * ``private=True``
  821. * ``no_cache=True``
  822. * ``no_transform=True``
  823. * ``must_revalidate=True``
  824. * ``proxy_revalidate=True``
  825. * ``max_age=num_seconds``
  826. * ``s_maxage=num_seconds``
  827. For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
  828. (Note that the caching middleware already sets the cache header's max-age with
  829. the value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. If you use a custom
  830. ``max_age`` in a ``cache_control`` decorator, the decorator will take
  831. precedence, and the header values will be merged correctly.)
  832. If you want to use headers to disable caching altogether,
  833. ``django.views.decorators.cache.never_cache`` is a view decorator that adds
  834. headers to ensure the response won't be cached by browsers or other caches.
  835. Example::
  836. from django.views.decorators.cache import never_cache
  837. @never_cache
  838. def myview(request):
  839. # ...
  840. .. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  841. Other optimizations
  842. ===================
  843. Django comes with a few other pieces of middleware that can help optimize your
  844. site's performance:
  845. * ``django.middleware.http.ConditionalGetMiddleware`` adds support for
  846. modern browsers to conditionally GET responses based on the ``ETag``
  847. and ``Last-Modified`` headers.
  848. * :class:`django.middleware.gzip.GZipMiddleware` compresses responses for all
  849. moderns browsers, saving bandwidth and transfer time.
  850. Order of MIDDLEWARE_CLASSES
  851. ===========================
  852. If you use caching middleware, it's important to put each half in the right
  853. place within the :setting:`MIDDLEWARE_CLASSES` setting. That's because the cache
  854. middleware needs to know which headers by which to vary the cache storage.
  855. Middleware always adds something to the ``Vary`` response header when it can.
  856. ``UpdateCacheMiddleware`` runs during the response phase, where middleware is
  857. run in reverse order, so an item at the top of the list runs *last* during the
  858. response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
  859. appears *before* any other middleware that might add something to the ``Vary``
  860. header. The following middleware modules do so:
  861. * ``SessionMiddleware`` adds ``Cookie``
  862. * ``GZipMiddleware`` adds ``Accept-Encoding``
  863. * ``LocaleMiddleware`` adds ``Accept-Language``
  864. ``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
  865. where middleware is applied first-to-last, so an item at the top of the list
  866. runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
  867. needs to run after other middleware updates the ``Vary`` header, so
  868. ``FetchFromCacheMiddleware`` must be *after* any item that does so.