cache.txt 46 KB

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