TEXT 32
Cache.txt Guest on 29th April 2021 06:46:53 AM
  1. ========================
  2. Django's cache framework
  3. ========================
  4.  
  5. A fundamental trade-off in dynamic Web sites is, well, they're dynamic. Each
  6. time a user requests a page, the Web server makes all sorts of calculations --
  7. from database queries to template rendering to business logic -- to create the
  8. page that your site's visitor sees. This is a lot more expensive, from a
  9. processing-overhead perspective, than your standard
  10. read-a-file-off-the-filesystem server arrangement.
  11.  
  12. For most Web applications, this overhead isn't a big deal. Most Web
  13. applications aren't ``washingtonpost.com`` or ``slashdot.org``; they're simply
  14. small- to medium-sized sites with so-so traffic. But for medium- to
  15. high-traffic sites, it's essential to cut as much overhead as possible.
  16.  
  17. That's where caching comes in.
  18.  
  19. To cache something is to save the result of an expensive calculation so that
  20. you don't have to perform the calculation next time. Here's some pseudocode
  21. explaining how this would work for a dynamically generated Web page::
  22.  
  23.     given a URL, try finding that page in the cache
  24.     if the page is in the cache:
  25.         return the cached page
  26.     else:
  27.         generate the page
  28.         save the generated page in the cache (for next time)
  29.         return the generated page
  30.  
  31. Django comes with a robust cache system that lets you save dynamic pages so
  32. they don't have to be calculated for each request. For convenience, Django
  33. offers different levels of cache granularity: You can cache the output of
  34. specific views, you can cache only the pieces that are difficult to produce,
  35. or you can cache your entire site.
  36.  
  37. Django also works well with "downstream" caches, such as `Squid
  38. <http://www.squid-cache.org>`_ and browser-based caches. These are the types of
  39. caches that you don't directly control but to which you can provide hints (via
  40. HTTP headers) about which parts of your site should be cached, and how.
  41.  
  42. .. seealso::
  43.     The :ref:`Cache Framework design philosophy <cache-design-philosophy>`
  44.     explains a few of the design decisions of the framework.
  45.  
  46. .. _setting-up-the-cache:
  47.  
  48. Setting up the cache
  49. ====================
  50.  
  51. The cache system requires a small amount of setup. Namely, you have to tell it
  52. where your cached data should live -- whether in a database, on the filesystem
  53. or directly in memory. This is an important decision that affects your cache's
  54. performance; yes, some cache types are faster than others.
  55.  
  56. Your cache preference goes in the :setting:`CACHES` setting in your
  57. settings file. Here's an explanation of all available values for
  58. :setting:`CACHES`.
  59.  
  60. .. _memcached:
  61.  
  62. Memcached
  63. ---------
  64.  
  65. The fastest, most efficient type of cache supported natively by Django,
  66. Memcached__ is an entirely memory-based cache server, originally developed
  67. to handle high loads at LiveJournal.com and subsequently open-sourced by
  68. Danga Interactive. It is used by sites such as Facebook and Wikipedia to
  69. reduce database access and dramatically increase site performance.
  70.  
  71. __ http://memcached.org/
  72.  
  73. Memcached runs as a daemon and is allotted a specified amount of RAM. All it
  74. does is provide a fast interface for adding, retrieving and deleting data in
  75. the cache. All data is stored directly in memory, so there's no overhead of
  76. database or filesystem usage.
  77.  
  78. After installing Memcached itself, you'll need to install a Memcached
  79. binding. There are several Python Memcached bindings available; the
  80. two most common are `python-memcached`_ and `pylibmc`_.
  81.  
  82. .. _`python-memcached`: ftp://ftp.tummy.com/pub/python-memcached/
  83. .. _`pylibmc`: http://sendapatch.se/projects/pylibmc/
  84.  
  85. To use Memcached with Django:
  86.  
  87. * Set :setting:`BACKEND <CACHES-BACKEND>` to
  88.   ``django.core.cache.backends.memcached.MemcachedCache`` or
  89.   ``django.core.cache.backends.memcached.PyLibMCCache`` (depending
  90.   on your chosen memcached binding)
  91.  
  92. * Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,
  93.   where ``ip`` is the IP address of the Memcached daemon and ``port`` is the
  94.   port on which Memcached is running, or to a ``unix:path`` value, where
  95.   ``path`` is the path to a Memcached Unix socket file.
  96.  
  97. In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
  98. the ``python-memcached`` binding::
  99.  
  100.     CACHES = {
  101.         'default': {
  102.             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  103.             'LOCATION': '127.0.0.1:11211',
  104.         }
  105.     }
  106.  
  107. In this example, Memcached is available through a local Unix socket file
  108. :file:`/tmp/memcached.sock` using the ``python-memcached`` binding::
  109.  
  110.     CACHES = {
  111.         'default': {
  112.             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  113.             'LOCATION': 'unix:/tmp/memcached.sock',
  114.         }
  115.     }
  116.  
  117. One excellent feature of Memcached is its ability to share a cache over
  118. multiple servers. This means you can run Memcached daemons on multiple
  119. machines, and the program will treat the group of machines as a *single*
  120. cache, without the need to duplicate cache values on each machine. To take
  121. advantage of this feature, include all server addresses in
  122. :setting:`LOCATION <CACHES-LOCATION>`, either separated by semicolons or as
  123. a list.
  124.  
  125. In this example, the cache is shared over Memcached instances running on IP
  126. address 172.19.26.240 and 172.19.26.242, both on port 11211::
  127.  
  128.     CACHES = {
  129.         'default': {
  130.             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  131.             'LOCATION': [
  132.                 '172.19.26.240:11211',
  133.                 '172.19.26.242:11211',
  134.             ]
  135.         }
  136.     }
  137.  
  138. In the following example, the cache is shared over Memcached instances running
  139. on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
  140. 172.19.26.244 (port 11213)::
  141.  
  142.     CACHES = {
  143.         'default': {
  144.             'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  145.             'LOCATION': [
  146.                 '172.19.26.240:11211',
  147.                 '172.19.26.242:11212',
  148.                 '172.19.26.244:11213',
  149.             ]
  150.         }
  151.     }
  152.  
  153. A final point about Memcached is that memory-based caching has a
  154. disadvantage: because the cached data is stored in memory, the data will be
  155. lost if your server crashes. Clearly, memory isn't intended for permanent data
  156. storage, so don't rely on memory-based caching as your only data storage.
  157. Without a doubt, *none* of the Django caching backends should be used for
  158. permanent storage -- they're all intended to be solutions for caching, not
  159. storage -- but we point this out here because memory-based caching is
  160. particularly temporary.
  161.  
  162. .. _database-caching:
  163.  
  164. Database caching
  165. ----------------
  166.  
  167. Django can store its cached data in your database. This works best if you've
  168. got a fast, well-indexed database server.
  169.  
  170. To use a database table as your cache backend:
  171.  
  172. * Set :setting:`BACKEND <CACHES-BACKEND>` to
  173.   ``django.core.cache.backends.db.DatabaseCache``
  174.  
  175. * Set :setting:`LOCATION <CACHES-LOCATION>` to ``tablename``, the name of the
  176.   database table. This name can be whatever you want, as long as it's a valid
  177.   table name that's not already being used in your database.
  178.  
  179. In this example, the cache table's name is ``my_cache_table``::
  180.  
  181.     CACHES = {
  182.         'default': {
  183.             'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
  184.             'LOCATION': 'my_cache_table',
  185.         }
  186.     }
  187.  
  188. Creating the cache table
  189. ~~~~~~~~~~~~~~~~~~~~~~~~
  190.  
  191. Before using the database cache, you must create the cache table with this
  192. command::
  193.  
  194.     python manage.py createcachetable
  195.  
  196. This creates a table in your database that is in the proper format that
  197. Django's database-cache system expects. The name of the table is taken from
  198. :setting:`LOCATION <CACHES-LOCATION>`.
  199.  
  200. If you are using multiple database caches, :djadmin:`createcachetable` creates
  201. one table for each cache.
  202.  
  203. If you are using multiple databases, :djadmin:`createcachetable` observes the
  204. ``allow_migrate()`` method of your database routers (see below).
  205.  
  206. Like :djadmin:`migrate`, :djadmin:`createcachetable` won't touch an existing
  207. table. It will only create missing tables.
  208.  
  209. .. versionchanged:: 1.7
  210.  
  211.     Before Django 1.7, :djadmin:`createcachetable` created one table at a time.
  212.     You had to pass the name of the table you wanted to create, and if you were
  213.     using multiple databases, you had to use the :djadminopt:`--database`
  214.     option. For backwards compatibility, this is still possible.
  215.  
  216. Multiple databases
  217. ~~~~~~~~~~~~~~~~~~
  218.  
  219. If you use database caching with multiple databases, you'll also need
  220. to set up routing instructions for your database cache table. For the
  221. purposes of routing, the database cache table appears as a model named
  222. ``CacheEntry``, in an application named ``django_cache``. This model
  223. won't appear in the models cache, but the model details can be used
  224. for routing purposes.
  225.  
  226. For example, the following router would direct all cache read
  227. operations to ``cache_replica``, and all write operations to
  228. ``cache_primary``. The cache table will only be synchronized onto
  229. ``cache_primary``::
  230.  
  231.     class CacheRouter(object):
  232.         """A router to control all database cache operations"""
  233.  
  234.         def db_for_read(self, model, **hints):
  235.             "All cache read operations go to the replica"
  236.             if model._meta.app_label == 'django_cache':
  237.                 return 'cache_replica'
  238.             return None
  239.  
  240.         def db_for_write(self, model, **hints):
  241.             "All cache write operations go to primary"
  242.             if model._meta.app_label == 'django_cache':
  243.                 return 'cache_primary'
  244.             return None
  245.  
  246.         def allow_migrate(self, db, app_label, model_name=None, **hints):
  247.             "Only install the cache model on primary"
  248.             if app_label == 'django_cache':
  249.                 return db == 'cache_primary'
  250.             return None
  251.  
  252. If you don't specify routing directions for the database cache model,
  253. the cache backend will use the ``default`` database.
  254.  
  255. Of course, if you don't use the database cache backend, you don't need
  256. to worry about providing routing instructions for the database cache
  257. model.
  258.  
  259. Filesystem caching
  260. ------------------
  261.  
  262. The file-based backend serializes and stores each cache value as a separate
  263. file. To use this backend set :setting:`BACKEND <CACHES-BACKEND>` to
  264. ``"django.core.cache.backends.filebased.FileBasedCache"`` and
  265. :setting:`LOCATION <CACHES-LOCATION>` to a suitable directory. For example,
  266. to store cached data in ``/var/tmp/django_cache``, use this setting::
  267.  
  268.     CACHES = {
  269.         'default': {
  270.             'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  271.             'LOCATION': '/var/tmp/django_cache',
  272.         }
  273.     }
  274.  
  275. If you're on Windows, put the drive letter at the beginning of the path,
  276. like this::
  277.  
  278.     CACHES = {
  279.         'default': {
  280.             'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  281.             'LOCATION': 'c:/foo/bar',
  282.         }
  283.     }
  284.  
  285. The directory path should be absolute -- that is, it should start at the root
  286. of your filesystem. It doesn't matter whether you put a slash at the end of the
  287. setting.
  288.  
  289. Make sure the directory pointed-to by this setting exists and is readable and
  290. writable by the system user under which your Web server runs. Continuing the
  291. above example, if your server runs as the user ``apache``, make sure the
  292. directory ``/var/tmp/django_cache`` exists and is readable and writable by the
  293. user ``apache``.
  294.  
  295. Local-memory caching
  296. --------------------
  297.  
  298. This is the default cache if another is not specified in your settings file. If
  299. you want the speed advantages of in-memory caching but don't have the capability
  300. of running Memcached, consider the local-memory cache backend. This cache is
  301. per-process (see below) and thread-safe. To use it, set :setting:`BACKEND
  302. <CACHES-BACKEND>` to ``"django.core.cache.backends.locmem.LocMemCache"``. For
  303. example::
  304.  
  305.     CACHES = {
  306.         'default': {
  307.             'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  308.             'LOCATION': 'unique-snowflake',
  309.         }
  310.     }
  311.  
  312. The cache :setting:`LOCATION <CACHES-LOCATION>` is used to identify individual
  313. memory stores. If you only have one ``locmem`` cache, you can omit the
  314. :setting:`LOCATION <CACHES-LOCATION>`; however, if you have more than one local
  315. memory cache, you will need to assign a name to at least one of them in
  316. order to keep them separate.
  317.  
  318. Note that each process will have its own private cache instance, which means no
  319. cross-process caching is possible. This obviously also means the local memory
  320. cache isn't particularly memory-efficient, so it's probably not a good choice
  321. for production environments. It's nice for development.
  322.  
  323. Dummy caching (for development)
  324. -------------------------------
  325.  
  326. Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
  327. just implements the cache interface without doing anything.
  328.  
  329. This is useful if you have a production site that uses heavy-duty caching in
  330. various places but a development/test environment where you don't want to cache
  331. and don't want to have to change your code to special-case the latter. To
  332. activate dummy caching, set :setting:`BACKEND <CACHES-BACKEND>` like so::
  333.  
  334.     CACHES = {
  335.         'default': {
  336.             'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
  337.         }
  338.     }
  339.  
  340. Using a custom cache backend
  341. ----------------------------
  342.  
  343. While Django includes support for a number of cache backends out-of-the-box,
  344. sometimes you might want to use a customized cache backend. To use an external
  345. cache backend with Django, use the Python import path as the
  346. :setting:`BACKEND <CACHES-BACKEND>` of the :setting:`CACHES` setting, like so::
  347.  
  348.     CACHES = {
  349.         'default': {
  350.             'BACKEND': 'path.to.backend',
  351.         }
  352.     }
  353.  
  354. If you're building your own backend, you can use the standard cache backends
  355. as reference implementations. You'll find the code in the
  356. ``django/core/cache/backends/`` directory of the Django source.
  357.  
  358. Note: Without a really compelling reason, such as a host that doesn't support
  359. them, you should stick to the cache backends included with Django. They've
  360. been well-tested and are easy to use.
  361.  
  362. Cache arguments
  363. ---------------
  364.  
  365. Each cache backend can be given additional arguments to control caching
  366. behavior. These arguments are provided as additional keys in the
  367. :setting:`CACHES` setting. Valid arguments are as follows:
  368.  
  369. * :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in
  370.   seconds, to use for the cache. This argument defaults to ``300`` seconds (5 minutes).
  371.  
  372.   .. versionadded:: 1.7
  373.  
  374.   You can set ``TIMEOUT`` to ``None`` so that, by default, cache keys never
  375.   expire. A value of ``0`` causes keys to immediately expire (effectively
  376.   "don't cache").
  377.  
  378. * :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be
  379.   passed to the cache backend. The list of valid options will vary
  380.   with each backend, and cache backends backed by a third-party library
  381.   will pass their options directly to the underlying cache library.
  382.  
  383.   Cache backends that implement their own culling strategy (i.e.,
  384.   the ``locmem``, ``filesystem`` and ``database`` backends) will
  385.   honor the following options:
  386.  
  387.   * ``MAX_ENTRIES``: The maximum number of entries allowed in
  388.     the cache before old values are deleted. This argument
  389.     defaults to ``300``.
  390.  
  391.   * ``CULL_FREQUENCY``: The fraction of entries that are culled
  392.     when ``MAX_ENTRIES`` is reached. The actual ratio is
  393.     ``1 / CULL_FREQUENCY``, so set ``CULL_FREQUENCY`` to ``2`` to
  394.     cull half the entries when ``MAX_ENTRIES`` is reached. This argument
  395.     should be an integer and defaults to ``3``.
  396.  
  397.     A value of ``0`` for ``CULL_FREQUENCY`` means that the
  398.     entire cache will be dumped when ``MAX_ENTRIES`` is reached.
  399.     On some backends (``database`` in particular) this makes culling *much*
  400.     faster at the expense of more cache misses.
  401.  
  402. * :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be
  403.   automatically included (prepended by default) to all cache keys
  404.   used by the Django server.
  405.  
  406.   See the :ref:`cache documentation <cache_key_prefixing>` for
  407.   more information.
  408.  
  409. * :setting:`VERSION <CACHES-VERSION>`: The default version number
  410.   for cache keys generated by the Django server.
  411.  
  412.   See the :ref:`cache documentation <cache_versioning>` for more
  413.   information.
  414.  
  415. * :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`
  416.   A string containing a dotted path to a function that defines how
  417.   to compose a prefix, version and key into a final cache key.
  418.  
  419.   See the :ref:`cache documentation <cache_key_transformation>`
  420.   for more information.
  421.  
  422. In this example, a filesystem backend is being configured with a timeout
  423. of 60 seconds, and a maximum capacity of 1000 items::
  424.  
  425.     CACHES = {
  426.         'default': {
  427.             'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  428.             'LOCATION': '/var/tmp/django_cache',
  429.             'TIMEOUT': 60,
  430.             'OPTIONS': {
  431.                 'MAX_ENTRIES': 1000
  432.             }
  433.         }
  434.     }
  435.  
  436. Invalid arguments are silently ignored, as are invalid values of known
  437. arguments.
  438.  
  439. .. _the-per-site-cache:
  440.  
  441. The per-site cache
  442. ==================
  443.  
  444. Once the cache is set up, the simplest way to use caching is to cache your
  445. entire site. You'll need to add
  446. ``'django.middleware.cache.UpdateCacheMiddleware'`` and
  447. ``'django.middleware.cache.FetchFromCacheMiddleware'`` to your
  448. :setting:`MIDDLEWARE_CLASSES` setting, as in this example::
  449.  
  450.     MIDDLEWARE_CLASSES = (
  451.         'django.middleware.cache.UpdateCacheMiddleware',
  452.         'django.middleware.common.CommonMiddleware',
  453.         'django.middleware.cache.FetchFromCacheMiddleware',
  454.     )
  455.  
  456. .. note::
  457.  
  458.     No, that's not a typo: the "update" middleware must be first in the list,
  459.     and the "fetch" middleware must be last. The details are a bit obscure, but
  460.     see `Order of MIDDLEWARE_CLASSES`_ below if you'd like the full story.
  461.  
  462. Then, add the following required settings to your Django settings file:
  463.  
  464. * :setting:`CACHE_MIDDLEWARE_ALIAS` -- The cache alias to use for storage.
  465. * :setting:`CACHE_MIDDLEWARE_SECONDS` -- The number of seconds each page should
  466.   be cached.
  467. * :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` -- If the cache is shared across
  468.   multiple sites using the same Django installation, set this to the name of
  469.   the site, or some other string that is unique to this Django instance, to
  470.   prevent key collisions. Use an empty string if you don't care.
  471.  
  472. ``FetchFromCacheMiddleware`` caches GET and HEAD responses with status 200,
  473. where the request and response headers allow. Responses to requests for the same
  474. URL with different query parameters are considered to be unique pages and are
  475. cached separately. This middleware expects that a HEAD request is answered with
  476. the same response headers as the corresponding GET request; in which case it can
  477. return a cached GET response for HEAD request.
  478.  
  479. Additionally, ``UpdateCacheMiddleware`` automatically sets a few headers in each
  480. :class:`~django.http.HttpResponse`:
  481.  
  482. * Sets the ``Last-Modified`` header to the current date/time when a fresh
  483.   (not cached) version of the page is requested.
  484.  
  485. * Sets the ``Expires`` header to the current date/time plus the defined
  486.   :setting:`CACHE_MIDDLEWARE_SECONDS`.
  487.  
  488. * Sets the ``Cache-Control`` header to give a max age for the page --
  489.   again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.
  490.  
  491. See :doc:`/topics/http/middleware` for more on middleware.
  492.  
  493. If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
  494. its ``Cache-Control`` header) then the page will be cached until the expiry
  495. time, rather than :setting:`CACHE_MIDDLEWARE_SECONDS`. Using the decorators in
  496. ``django.views.decorators.cache`` you can easily set a view's expiry time
  497. (using the ``cache_control`` decorator) or disable caching for a view (using
  498. the ``never_cache`` decorator). See the `using other headers`__ section for
  499. more on these decorators.
  500.  
  501. .. _i18n-cache-key:
  502.  
  503. If :setting:`USE_I18N` is set to ``True`` then the generated cache key will
  504. include the name of the active :term:`language<language code>` -- see also
  505. :ref:`how-django-discovers-language-preference`). This allows you to easily
  506. cache multilingual sites without having to create the cache key yourself.
  507.  
  508. Cache keys also include the active :term:`language <language code>` when
  509. :setting:`USE_L10N` is set to ``True`` and the :ref:`current time zone
  510. <default-current-time-zone>` when :setting:`USE_TZ` is set to ``True``.
  511.  
  512. __ `Controlling cache: Using other headers`_
  513.  
  514. The per-view cache
  515. ==================
  516.  
  517. .. function:: django.views.decorators.cache.cache_page
  518.  
  519. A more granular way to use the caching framework is by caching the output of
  520. individual views. ``django.views.decorators.cache`` defines a ``cache_page``
  521. decorator that will automatically cache the view's response for you. It's easy
  522. to use::
  523.  
  524.     from django.views.decorators.cache import cache_page
  525.  
  526.     @cache_page(60 * 15)
  527.     def my_view(request):
  528.         ...
  529.  
  530. ``cache_page`` takes a single argument: the cache timeout, in seconds. In the
  531. above example, the result of the ``my_view()`` view will be cached for 15
  532. minutes. (Note that we've written it as ``60 * 15`` for the purpose of
  533. readability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes
  534. multiplied by 60 seconds per minute.)
  535.  
  536. The per-view cache, like the per-site cache, is keyed off of the URL. If
  537. multiple URLs point at the same view, each URL will be cached separately.
  538. Continuing the ``my_view`` example, if your URLconf looks like this::
  539.  
  540.     urlpatterns = [
  541.         url(r'^foo/([0-9]{1,2})/$', my_view),
  542.     ]
  543.  
  544. then requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as
  545. you may expect. But once a particular URL (e.g., ``/foo/23/``) has been
  546. requested, subsequent requests to that URL will use the cache.
  547.  
  548. ``cache_page`` can also take an optional keyword argument, ``cache``,
  549. which directs the decorator to use a specific cache (from your
  550. :setting:`CACHES` setting) when caching view results. By default, the
  551. ``default`` cache will be used, but you can specify any cache you
  552. want::
  553.  
  554.     @cache_page(60 * 15, cache="special_cache")
  555.     def my_view(request):
  556.         ...
  557.  
  558. You can also override the cache prefix on a per-view basis. ``cache_page``
  559. takes an optional keyword argument, ``key_prefix``,
  560. which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`
  561. setting for the middleware.  It can be used like this::
  562.  
  563.     @cache_page(60 * 15, key_prefix="site1")
  564.     def my_view(request):
  565.         ...
  566.  
  567. The ``key_prefix`` and ``cache`` arguments may be specified together. The
  568. ``key_prefix`` argument and the :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`
  569. specified under :setting:`CACHES` will be concatenated.
  570.  
  571. Specifying per-view cache in the URLconf
  572. ----------------------------------------
  573.  
  574. The examples in the previous section have hard-coded the fact that the view is
  575. cached, because ``cache_page`` alters the ``my_view`` function in place. This
  576. approach couples your view to the cache system, which is not ideal for several
  577. reasons. For instance, you might want to reuse the view functions on another,
  578. cache-less site, or you might want to distribute the views to people who might
  579. want to use them without being cached. The solution to these problems is to
  580. specify the per-view cache in the URLconf rather than next to the view functions
  581. themselves.
  582.  
  583. Doing so is easy: simply wrap the view function with ``cache_page`` when you
  584. refer to it in the URLconf. Here's the old URLconf from earlier::
  585.  
  586.     urlpatterns = [
  587.         url(r'^foo/([0-9]{1,2})/$', my_view),
  588.     ]
  589.  
  590. Here's the same thing, with ``my_view`` wrapped in ``cache_page``::
  591.  
  592.     from django.views.decorators.cache import cache_page
  593.  
  594.     urlpatterns = [
  595.         url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
  596.     ]
  597.  
  598. .. templatetag:: cache
  599.  
  600. Template fragment caching
  601. =========================
  602.  
  603. If you're after even more control, you can also cache template fragments using
  604. the ``cache`` template tag. To give your template access to this tag, put
  605. ``{% load cache %}`` near the top of your template.
  606.  
  607. The ``{% cache %}`` template tag caches the contents of the block for a given
  608. amount of time. It takes at least two arguments: the cache timeout, in seconds,
  609. and the name to give the cache fragment. The name will be taken as is, do not
  610. use a variable. For example:
  611.  
  612. .. code-block:: html+django
  613.  
  614.     {% load cache %}
  615.     {% cache 500 sidebar %}
  616.         .. sidebar ..
  617.     {% endcache %}
  618.  
  619. Sometimes you might want to cache multiple copies of a fragment depending on
  620. some dynamic data that appears inside the fragment. For example, you might want a
  621. separate cached copy of the sidebar used in the previous example for every user
  622. of your site. Do this by passing additional arguments to the ``{% cache %}``
  623. template tag to uniquely identify the cache fragment:
  624.  
  625. .. code-block:: html+django
  626.  
  627.     {% load cache %}
  628.     {% cache 500 sidebar request.user.username %}
  629.         .. sidebar for logged in user ..
  630.     {% endcache %}
  631.  
  632. It's perfectly fine to specify more than one argument to identify the fragment.
  633. Simply pass as many arguments to ``{% cache %}`` as you need.
  634.  
  635. If :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will
  636. :ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template
  637. tag you could use one of the
  638. :ref:`translation-specific variables<template-translation-vars>` available in
  639. templates to achieve the same result:
  640.  
  641. .. code-block:: html+django
  642.  
  643.     {% load i18n %}
  644.     {% load cache %}
  645.  
  646.     {% get_current_language as LANGUAGE_CODE %}
  647.  
  648.     {% cache 600 welcome LANGUAGE_CODE %}
  649.         {% trans "Welcome to example.com" %}
  650.     {% endcache %}
  651.  
  652. The cache timeout can be a template variable, as long as the template variable
  653. resolves to an integer value. For example, if the template variable
  654. ``my_timeout`` is set to the value ``600``, then the following two examples are
  655. equivalent:
  656.  
  657. .. code-block:: html+django
  658.  
  659.     {% cache 600 sidebar %} ... {% endcache %}
  660.     {% cache my_timeout sidebar %} ... {% endcache %}
  661.  
  662. This feature is useful in avoiding repetition in templates. You can set the
  663. timeout in a variable, in one place, and just reuse that value.
  664.  
  665. .. versionadded:: 1.7
  666.  
  667.     By default, the cache tag will try to use the cache called
  668.     "template_fragments". If no such cache exists, it will fall back to using
  669.     the default cache. You may select an alternate cache backend to use with
  670.     the ``using`` keyword argument, which must be the last argument to the tag.
  671.  
  672. .. code-block:: html+django
  673.  
  674.     {% cache 300 local-thing ...  using="localcache" %}
  675.  
  676. It is considered an error to specify a cache name that is not configured.
  677.  
  678. .. function:: django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None)
  679.  
  680. If you want to obtain the cache key used for a cached fragment, you can use
  681. ``make_template_fragment_key``. ``fragment_name`` is the same as second argument
  682. to the ``cache`` template tag; ``vary_on`` is a list of all additional arguments
  683. passed to the tag. This function can be useful for invalidating or overwriting
  684. a cached item, for example:
  685.  
  686. .. code-block:: pycon
  687.  
  688.     >>> from django.core.cache import cache
  689.     >>> from django.core.cache.utils import make_template_fragment_key
  690.     # cache key for {% cache 500 sidebar username %}
  691.     >>> key = make_template_fragment_key('sidebar', [username])
  692.     >>> cache.delete(key) # invalidates cached template fragment
  693.  
  694.  
  695. The low-level cache API
  696. =======================
  697.  
  698. .. highlight:: python
  699.  
  700. Sometimes, caching an entire rendered page doesn't gain you very much and is,
  701. in fact, inconvenient overkill.
  702.  
  703. Perhaps, for instance, your site includes a view whose results depend on
  704. several expensive queries, the results of which change at different intervals.
  705. In this case, it would not be ideal to use the full-page caching that the
  706. per-site or per-view cache strategies offer, because you wouldn't want to
  707. cache the entire result (since some of the data changes often), but you'd still
  708. want to cache the results that rarely change.
  709.  
  710. For cases like this, Django exposes a simple, low-level cache API. You can use
  711. this API to store objects in the cache with any level of granularity you like.
  712. You can cache any Python object that can be pickled safely: strings,
  713. dictionaries, lists of model objects, and so forth. (Most common Python objects
  714. can be pickled; refer to the Python documentation for more information about
  715. pickling.)
  716.  
  717. Accessing the cache
  718. -------------------
  719.  
  720. .. data:: django.core.cache.caches
  721.  
  722.     .. versionadded:: 1.7
  723.  
  724.     You can access the caches configured in the :setting:`CACHES` setting
  725.     through a dict-like object: ``django.core.cache.caches``. Repeated
  726.     requests for the same alias in the same thread will return the same
  727.     object.
  728.  
  729.         >>> from django.core.cache import caches
  730.         >>> cache1 = caches['myalias']
  731.         >>> cache2 = caches['myalias']
  732.         >>> cache1 is cache2
  733.         True
  734.  
  735.     If the named key does not exist, ``InvalidCacheBackendError`` will be
  736.     raised.
  737.  
  738.     To provide thread-safety, a different instance of the cache backend will
  739.     be returned for each thread.
  740.  
  741. .. data:: django.core.cache.cache
  742.  
  743.     As a shortcut, the default cache is available as
  744.     ``django.core.cache.cache``::
  745.  
  746.         >>> from django.core.cache import cache
  747.  
  748.     This object is equivalent to ``caches['default']``.
  749.  
  750. .. function:: django.core.cache.get_cache(backend, **kwargs)
  751.  
  752.     .. deprecated:: 1.7
  753.         This function has been deprecated in favor of
  754.         :data:`~django.core.cache.caches`.
  755.  
  756.     Before Django 1.7 this function was the canonical way to obtain a cache
  757.     instance. It could also be used to create a new cache instance with a
  758.     different configuration.
  759.  
  760.         >>> from django.core.cache import get_cache
  761.         >>> get_cache('default')
  762.         >>> get_cache('django.core.cache.backends.memcached.MemcachedCache', LOCATION='127.0.0.2')
  763.         >>> get_cache('default', TIMEOUT=300)
  764.  
  765. Basic usage
  766. -----------
  767.  
  768. The basic interface is ``set(key, value, timeout)`` and ``get(key)``::
  769.  
  770.     >>> cache.set('my_key', 'hello, world!', 30)
  771.     >>> cache.get('my_key')
  772.     'hello, world!'
  773.  
  774. The ``timeout`` argument is optional and defaults to the ``timeout`` argument
  775. of the appropriate backend in the :setting:`CACHES` setting (explained above).
  776. It's the number of seconds the value should be stored in the cache. Passing in
  777. ``None`` for ``timeout`` will cache the value forever. A ``timeout`` of ``0``
  778. won't cache the value.
  779.  
  780. If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
  781.  
  782.     # Wait 30 seconds for 'my_key' to expire...
  783.  
  784.     >>> cache.get('my_key')
  785.     None
  786.  
  787. We advise against storing the literal value ``None`` in the cache, because you
  788. won't be able to distinguish between your stored ``None`` value and a cache
  789. miss signified by a return value of ``None``.
  790.  
  791. ``cache.get()`` can take a ``default`` argument. This specifies which value to
  792. return if the object doesn't exist in the cache::
  793.  
  794.     >>> cache.get('my_key', 'has expired')
  795.     'has expired'
  796.  
  797. To add a key only if it doesn't already exist, use the ``add()`` method.
  798. It takes the same parameters as ``set()``, but it will not attempt to
  799. update the cache if the key specified is already present::
  800.  
  801.     >>> cache.set('add_key', 'Initial value')
  802.     >>> cache.add('add_key', 'New value')
  803.     >>> cache.get('add_key')
  804.     'Initial value'
  805.  
  806. If you need to know whether ``add()`` stored a value in the cache, you can
  807. check the return value. It will return ``True`` if the value was stored,
  808. ``False`` otherwise.
  809.  
  810. There's also a ``get_many()`` interface that only hits the cache once.
  811. ``get_many()`` returns a dictionary with all the keys you asked for that
  812. actually exist in the cache (and haven't expired)::
  813.  
  814.     >>> cache.set('a', 1)
  815.     >>> cache.set('b', 2)
  816.     >>> cache.set('c', 3)
  817.     >>> cache.get_many(['a', 'b', 'c'])
  818.     {'a': 1, 'b': 2, 'c': 3}
  819.  
  820. To set multiple values more efficiently, use ``set_many()`` to pass a dictionary
  821. of key-value pairs::
  822.  
  823.     >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})
  824.     >>> cache.get_many(['a', 'b', 'c'])
  825.     {'a': 1, 'b': 2, 'c': 3}
  826.  
  827. Like ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.
  828.  
  829. You can delete keys explicitly with ``delete()``. This is an easy way of
  830. clearing the cache for a particular object::
  831.  
  832.     >>> cache.delete('a')
  833.  
  834. If you want to clear a bunch of keys at once, ``delete_many()`` can take a list
  835. of keys to be cleared::
  836.  
  837.     >>> cache.delete_many(['a', 'b', 'c'])
  838.  
  839. Finally, if you want to delete all the keys in the cache, use
  840. ``cache.clear()``.  Be careful with this; ``clear()`` will remove *everything*
  841. from the cache, not just the keys set by your application. ::
  842.  
  843.     >>> cache.clear()
  844.  
  845. You can also increment or decrement a key that already exists using the
  846. ``incr()`` or ``decr()`` methods, respectively. By default, the existing cache
  847. value will incremented or decremented by 1. Other increment/decrement values
  848. can be specified by providing an argument to the increment/decrement call. A
  849. ValueError will be raised if you attempt to increment or decrement a
  850. nonexistent cache key.::
  851.  
  852.     >>> cache.set('num', 1)
  853.     >>> cache.incr('num')
  854.     2
  855.     >>> cache.incr('num', 10)
  856.     12
  857.     >>> cache.decr('num')
  858.     11
  859.     >>> cache.decr('num', 5)
  860.     6
  861.  
  862. .. note::
  863.  
  864.     ``incr()``/``decr()`` methods are not guaranteed to be atomic. On those
  865.     backends that support atomic increment/decrement (most notably, the
  866.     memcached backend), increment and decrement operations will be atomic.
  867.     However, if the backend doesn't natively provide an increment/decrement
  868.     operation, it will be implemented using a two-step retrieve/update.
  869.  
  870.  
  871. You can close the connection to your cache with ``close()`` if implemented by
  872. the cache backend.
  873.  
  874.     >>> cache.close()
  875.  
  876. .. note::
  877.  
  878.     For caches that don't implement ``close`` methods it is a no-op.
  879.  
  880. .. _cache_key_prefixing:
  881.  
  882. Cache key prefixing
  883. -------------------
  884.  
  885. If you are sharing a cache instance between servers, or between your
  886. production and development environments, it's possible for data cached
  887. by one server to be used by another server. If the format of cached
  888. data is different between servers, this can lead to some very hard to
  889. diagnose problems.
  890.  
  891. To prevent this, Django provides the ability to prefix all cache keys
  892. used by a server. When a particular cache key is saved or retrieved,
  893. Django will automatically prefix the cache key with the value of the
  894. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` cache setting.
  895.  
  896. By ensuring each Django instance has a different
  897. :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`, you can ensure that there will be no
  898. collisions in cache values.
  899.  
  900. .. _cache_versioning:
  901.  
  902. Cache versioning
  903. ----------------
  904.  
  905. When you change running code that uses cached values, you may need to
  906. purge any existing cached values. The easiest way to do this is to
  907. flush the entire cache, but this can lead to the loss of cache values
  908. that are still valid and useful.
  909.  
  910. Django provides a better way to target individual cache values.
  911. Django's cache framework has a system-wide version identifier,
  912. specified using the :setting:`VERSION <CACHES-VERSION>` cache setting.
  913. The value of this setting is automatically combined with the cache
  914. prefix and the user-provided cache key to obtain the final cache key.
  915.  
  916. By default, any key request will automatically include the site
  917. default cache key version. However, the primitive cache functions all
  918. include a ``version`` argument, so you can specify a particular cache
  919. key version to set or get. For example::
  920.  
  921.     # Set version 2 of a cache key
  922.     >>> cache.set('my_key', 'hello world!', version=2)
  923.     # Get the default version (assuming version=1)
  924.     >>> cache.get('my_key')
  925.     None
  926.     # Get version 2 of the same key
  927.     >>> cache.get('my_key', version=2)
  928.     'hello world!'
  929.  
  930. The version of a specific key can be incremented and decremented using
  931. the ``incr_version()`` and ``decr_version()`` methods. This
  932. enables specific keys to be bumped to a new version, leaving other
  933. keys unaffected. Continuing our previous example::
  934.  
  935.     # Increment the version of 'my_key'
  936.     >>> cache.incr_version('my_key')
  937.     # The default version still isn't available
  938.     >>> cache.get('my_key')
  939.     None
  940.     # Version 2 isn't available, either
  941.     >>> cache.get('my_key', version=2)
  942.     None
  943.     # But version 3 *is* available
  944.     >>> cache.get('my_key', version=3)
  945.     'hello world!'
  946.  
  947. .. _cache_key_transformation:
  948.  
  949. Cache key transformation
  950. ------------------------
  951.  
  952. As described in the previous two sections, the cache key provided by a
  953. user is not used verbatim -- it is combined with the cache prefix and
  954. key version to provide a final cache key. By default, the three parts
  955. are joined using colons to produce a final string::
  956.  
  957.     def make_key(key, key_prefix, version):
  958.         return ':'.join([key_prefix, str(version), key])
  959.  
  960. If you want to combine the parts in different ways, or apply other
  961. processing to the final key (e.g., taking a hash digest of the key
  962. parts), you can provide a custom key function.
  963.  
  964. The :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting
  965. specifies a dotted-path to a function matching the prototype of
  966. ``make_key()`` above. If provided, this custom key function will
  967. be used instead of the default key combining function.
  968.  
  969. Cache key warnings
  970. ------------------
  971.  
  972. Memcached, the most commonly-used production cache backend, does not allow
  973. cache keys longer than 250 characters or containing whitespace or control
  974. characters, and using such keys will cause an exception. To encourage
  975. cache-portable code and minimize unpleasant surprises, the other built-in cache
  976. backends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``)
  977. if a key is used that would cause an error on memcached.
  978.  
  979. If you are using a production backend that can accept a wider range of keys (a
  980. custom backend, or one of the non-memcached built-in backends), and want to use
  981. this wider range without warnings, you can silence ``CacheKeyWarning`` with
  982. this code in the ``management`` module of one of your
  983. :setting:`INSTALLED_APPS`::
  984.  
  985.      import warnings
  986.  
  987.      from django.core.cache import CacheKeyWarning
  988.  
  989.      warnings.simplefilter("ignore", CacheKeyWarning)
  990.  
  991. If you want to instead provide custom key validation logic for one of the
  992. built-in backends, you can subclass it, override just the ``validate_key``
  993. method, and follow the instructions for `using a custom cache backend`_. For
  994. instance, to do this for the ``locmem`` backend, put this code in a module::
  995.  
  996.     from django.core.cache.backends.locmem import LocMemCache
  997.  
  998.     class CustomLocMemCache(LocMemCache):
  999.         def validate_key(self, key):
  1000.             """Custom validation, raising exceptions or warnings as needed."""
  1001.             # ...
  1002.  
  1003. ...and use the dotted Python path to this class in the
  1004. :setting:`BACKEND <CACHES-BACKEND>` portion of your :setting:`CACHES` setting.
  1005.  
  1006. Downstream caches
  1007. =================
  1008.  
  1009. So far, this document has focused on caching your *own* data. But another type
  1010. of caching is relevant to Web development, too: caching performed by
  1011. "downstream" caches. These are systems that cache pages for users even before
  1012. the request reaches your Web site.
  1013.  
  1014. Here are a few examples of downstream caches:
  1015.  
  1016. * Your ISP may cache certain pages, so if you requested a page from
  1017.   http://example.com/, your ISP would send you the page without having to
  1018.   access example.com directly. The maintainers of example.com have no
  1019.   knowledge of this caching; the ISP sits between example.com and your Web
  1020.   browser, handling all of the caching transparently.
  1021.  
  1022. * Your Django Web site may sit behind a *proxy cache*, such as Squid Web
  1023.   Proxy Cache (http://www.squid-cache.org/), that caches pages for
  1024.   performance. In this case, each request first would be handled by the
  1025.   proxy, and it would be passed to your application only if needed.
  1026.  
  1027. * Your Web browser caches pages, too. If a Web page sends out the
  1028.   appropriate headers, your browser will use the local cached copy for
  1029.   subsequent requests to that page, without even contacting the Web page
  1030.   again to see whether it has changed.
  1031.  
  1032. Downstream caching is a nice efficiency boost, but there's a danger to it:
  1033. Many Web pages' contents differ based on authentication and a host of other
  1034. variables, and cache systems that blindly save pages based purely on URLs could
  1035. expose incorrect or sensitive data to subsequent visitors to those pages.
  1036.  
  1037. For example, say you operate a Web email system, and the contents of the
  1038. "inbox" page obviously depend on which user is logged in. If an ISP blindly
  1039. cached your site, then the first user who logged in through that ISP would have
  1040. their user-specific inbox page cached for subsequent visitors to the site.
  1041. That's not cool.
  1042.  
  1043. Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
  1044. exist to instruct downstream caches to differ their cache contents depending on
  1045. designated variables, and to tell caching mechanisms not to cache particular
  1046. pages. We'll look at some of these headers in the sections that follow.
  1047.  
  1048. .. _using-vary-headers:
  1049.  
  1050. Using Vary headers
  1051. ==================
  1052.  
  1053. The ``Vary`` header defines which request headers a cache
  1054. mechanism should take into account when building its cache key. For example, if
  1055. the contents of a Web page depend on a user's language preference, the page is
  1056. said to "vary on language."
  1057.  
  1058. By default, Django's cache system creates its cache keys using the requested
  1059. fully-qualified URL -- e.g.,
  1060. ``"http://www.example.com/stories/2005/?order_by=author"``. This means every
  1061. request to that URL will use the same cached version, regardless of user-agent
  1062. differences such as cookies or language preferences. However, if this page
  1063. produces different content based on some difference in request headers -- such
  1064. as a cookie, or a language, or a user-agent -- you'll need to use the ``Vary``
  1065. header to tell caching mechanisms that the page output depends on those things.
  1066.  
  1067. .. versionchanged:: 1.7
  1068.  
  1069.     Cache keys use the request's fully-qualified URL rather than just the path
  1070.     and query string.
  1071.  
  1072. To do this in Django, use the convenient
  1073. :func:`django.views.decorators.vary.vary_on_headers` view decorator, like so::
  1074.  
  1075.     from django.views.decorators.vary import vary_on_headers
  1076.  
  1077.     @vary_on_headers('User-Agent')
  1078.     def my_view(request):
  1079.         # ...
  1080.  
  1081. In this case, a caching mechanism (such as Django's own cache middleware) will
  1082. cache a separate version of the page for each unique user-agent.
  1083.  
  1084. The advantage to using the ``vary_on_headers`` decorator rather than manually
  1085. setting the ``Vary`` header (using something like
  1086. ``response['Vary'] = 'user-agent'``) is that the decorator *adds* to the
  1087. ``Vary`` header (which may already exist), rather than setting it from scratch
  1088. and potentially overriding anything that was already in there.
  1089.  
  1090. You can pass multiple headers to ``vary_on_headers()``::
  1091.  
  1092.     @vary_on_headers('User-Agent', 'Cookie')
  1093.     def my_view(request):
  1094.         # ...
  1095.  
  1096. This tells downstream caches to vary on *both*, which means each combination of
  1097. user-agent and cookie will get its own cache value. For example, a request with
  1098. the user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered
  1099. different from a request with the user-agent ``Mozilla`` and the cookie value
  1100. ``foo=ham``.
  1101.  
  1102. Because varying on cookie is so common, there's a
  1103. :func:`django.views.decorators.vary.vary_on_cookie` decorator. These two views
  1104. are equivalent::
  1105.  
  1106.     @vary_on_cookie
  1107.     def my_view(request):
  1108.         # ...
  1109.  
  1110.     @vary_on_headers('Cookie')
  1111.     def my_view(request):
  1112.         # ...
  1113.  
  1114. The headers you pass to ``vary_on_headers`` are not case sensitive;
  1115. ``"User-Agent"`` is the same thing as ``"user-agent"``.
  1116.  
  1117. You can also use a helper function, :func:`django.utils.cache.patch_vary_headers`,
  1118. directly. This function sets, or adds to, the ``Vary header``. For example::
  1119.  
  1120.     from django.utils.cache import patch_vary_headers
  1121.  
  1122.     def my_view(request):
  1123.         # ...
  1124.         response = render_to_response('template_name', context)
  1125.         patch_vary_headers(response, ['Cookie'])
  1126.         return response
  1127.  
  1128. ``patch_vary_headers`` takes an :class:`~django.http.HttpResponse` instance as
  1129. its first argument and a list/tuple of case-insensitive header names as its
  1130. second argument.
  1131.  
  1132. For more on Vary headers, see the `official Vary spec`_.
  1133.  
  1134. .. _`official Vary spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
  1135.  
  1136. Controlling cache: Using other headers
  1137. ======================================
  1138.  
  1139. Other problems with caching are the privacy of data and the question of where
  1140. data should be stored in a cascade of caches.
  1141.  
  1142. A user usually faces two kinds of caches: their own browser cache (a private
  1143. cache) and their provider's cache (a public cache). A public cache is used by
  1144. multiple users and controlled by someone else. This poses problems with
  1145. sensitive data--you don't want, say, your bank account number stored in a
  1146. public cache. So Web applications need a way to tell caches which data is
  1147. private and which is public.
  1148.  
  1149. The solution is to indicate a page's cache should be "private." To do this in
  1150. Django, use the ``cache_control`` view decorator. Example::
  1151.  
  1152.     from django.views.decorators.cache import cache_control
  1153.  
  1154.     @cache_control(private=True)
  1155.     def my_view(request):
  1156.         # ...
  1157.  
  1158. This decorator takes care of sending out the appropriate HTTP header behind the
  1159. scenes.
  1160.  
  1161. Note that the cache control settings "private" and "public" are mutually
  1162. exclusive. The decorator ensures that the "public" directive is removed if
  1163. "private" should be set (and vice versa). An example use of the two directives
  1164. would be a blog site that offers both private and public entries. Public
  1165. entries may be cached on any shared cache. The following code uses
  1166. :func:`django.utils.cache.patch_cache_control`, the manual way to modify the
  1167. cache control header (it is internally called by the ``cache_control``
  1168. decorator)::
  1169.  
  1170.     from django.views.decorators.cache import patch_cache_control
  1171.     from django.views.decorators.vary import vary_on_cookie
  1172.  
  1173.     @vary_on_cookie
  1174.     def list_blog_entries_view(request):
  1175.         if request.user.is_anonymous():
  1176.             response = render_only_public_entries()
  1177.             patch_cache_control(response, public=True)
  1178.         else:
  1179.             response = render_private_and_public_entries(request.user)
  1180.             patch_cache_control(response, private=True)
  1181.  
  1182.         return response
  1183.  
  1184. There are a few other ways to control cache parameters. For example, HTTP
  1185. allows applications to do the following:
  1186.  
  1187. * Define the maximum time a page should be cached.
  1188.  
  1189. * Specify whether a cache should always check for newer versions, only
  1190.   delivering the cached content when there are no changes. (Some caches
  1191.   might deliver cached content even if the server page changed, simply
  1192.   because the cache copy isn't yet expired.)
  1193.  
  1194. In Django, use the ``cache_control`` view decorator to specify these cache
  1195. parameters. In this example, ``cache_control`` tells caches to revalidate the
  1196. cache on every access and to store cached versions for, at most, 3,600 seconds::
  1197.  
  1198.     from django.views.decorators.cache import cache_control
  1199.  
  1200.     @cache_control(must_revalidate=True, max_age=3600)
  1201.     def my_view(request):
  1202.         # ...
  1203.  
  1204. Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
  1205. Here's a full list:
  1206.  
  1207. * ``public=True``
  1208. * ``private=True``
  1209. * ``no_cache=True``
  1210. * ``no_transform=True``
  1211. * ``must_revalidate=True``
  1212. * ``proxy_revalidate=True``
  1213. * ``max_age=num_seconds``
  1214. * ``s_maxage=num_seconds``
  1215.  
  1216. For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
  1217.  
  1218. (Note that the caching middleware already sets the cache header's max-age with
  1219. the value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. If you use a custom
  1220. ``max_age`` in a ``cache_control`` decorator, the decorator will take
  1221. precedence, and the header values will be merged correctly.)
  1222.  
  1223. If you want to use headers to disable caching altogether,
  1224. ``django.views.decorators.cache.never_cache`` is a view decorator that adds
  1225. headers to ensure the response won't be cached by browsers or other caches.
  1226. Example::
  1227.  
  1228.     from django.views.decorators.cache import never_cache
  1229.  
  1230.     @never_cache
  1231.     def myview(request):
  1232.         # ...
  1233.  
  1234. .. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  1235.  
  1236. Order of MIDDLEWARE_CLASSES
  1237. ===========================
  1238.  
  1239. If you use caching middleware, it's important to put each half in the right
  1240. place within the :setting:`MIDDLEWARE_CLASSES` setting. That's because the cache
  1241. middleware needs to know which headers by which to vary the cache storage.
  1242. Middleware always adds something to the ``Vary`` response header when it can.
  1243.  
  1244. ``UpdateCacheMiddleware`` runs during the response phase, where middleware is
  1245. run in reverse order, so an item at the top of the list runs *last* during the
  1246. response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
  1247. appears *before* any other middleware that might add something to the ``Vary``
  1248. header. The following middleware modules do so:
  1249.  
  1250. * ``SessionMiddleware`` adds ``Cookie``
  1251. * ``GZipMiddleware`` adds ``Accept-Encoding``
  1252. * ``LocaleMiddleware`` adds ``Accept-Language``
  1253.  
  1254. ``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
  1255. where middleware is applied first-to-last, so an item at the top of the list
  1256. runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
  1257. needs to run after other middleware updates the ``Vary`` header, so
  1258. ``FetchFromCacheMiddleware`` must be *after* any item that does so.

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.