cache.txt 46 KB

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