Fixed #8234: Corrected typo in docs/cache.txt
[django.git] / docs / cache.txt
blob8f3134e3bc18711bb4e9d092b3f8fe147441f778
1 ========================
2 Django's cache framework
3 ========================
5 A fundamental tradeoff 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.
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 small-
14 to medium-sized sites with so-so traffic. But for medium- to high-traffic
15 sites, it's essential to cut as much overhead as possible.
17 That's where caching comes in.
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::
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
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, or
35 you can cache your entire site.
37 Django also works well with "upstream" 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.
42 Setting up the cache
43 ====================
45 The cache system requires a small amount of setup. Namely, you have to tell it
46 where your cached data should live -- whether in a database, on the filesystem
47 or directly in memory. This is an important decision that affects your cache's
48 performance; yes, some cache types are faster than others.
50 Your cache preference goes in the ``CACHE_BACKEND`` setting in your settings
51 file. Here's an explanation of all available values for CACHE_BACKEND.
53 Memcached
54 ---------
56 By far the fastest, most efficient type of cache available to Django, Memcached
57 is an entirely memory-based cache framework originally developed to handle high
58 loads at LiveJournal.com and subsequently open-sourced by Danga Interactive.
59 It's used by sites such as Slashdot and Wikipedia to reduce database access and
60 dramatically increase site performance.
62 Memcached is available for free at http://danga.com/memcached/ . It runs as a
63 daemon and is allotted a specified amount of RAM. All it does is provide an
64 interface -- a *super-lightning-fast* interface -- for adding, retrieving and
65 deleting arbitrary data in the cache. All data is stored directly in memory,
66 so there's no overhead of database or filesystem usage.
68 After installing Memcached itself, you'll need to install the Memcached Python
69 bindings. Two versions of this are available. Choose and install *one* of the
70 following modules:
72     * The fastest available option is a module called ``cmemcache``, available
73       at http://gijsbert.org/cmemcache/ . (This module is only compatible with
74       the Django development version. Django 0.96 is only compatible with the
75       second option, below.)
77     * If you can't install ``cmemcache``, you can install ``python-memcached``,
78       available at ftp://ftp.tummy.com/pub/python-memcached/ . If that URL is
79       no longer valid, just go to the Memcached Web site
80       (http://www.danga.com/memcached/) and get the Python bindings from the
81       "Client APIs" section.
83 To use Memcached with Django, set ``CACHE_BACKEND`` to
84 ``memcached://ip:port/``, where ``ip`` is the IP address of the Memcached
85 daemon and ``port`` is the port on which Memcached is running.
87 In this example, Memcached is running on localhost (127.0.0.1) port 11211::
89     CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
91 One excellent feature of Memcached is its ability to share cache over multiple
92 servers. To take advantage of this feature, include all server addresses in
93 ``CACHE_BACKEND``, separated by semicolons. In this example, the cache is
94 shared over Memcached instances running on IP address 172.19.26.240 and
95 172.19.26.242, both on port 11211::
97     CACHE_BACKEND = 'memcached://172.19.26.240:11211;172.19.26.242:11211/'
99 Memory-based caching has one disadvantage: Because the cached data is stored in
100 memory, the data will be lost if your server crashes. Clearly, memory isn't
101 intended for permanent data storage, so don't rely on memory-based caching as
102 your only data storage. Actually, none of the Django caching backends should be
103 used for permanent storage -- they're all intended to be solutions for caching,
104 not storage -- but we point this out here because memory-based caching is
105 particularly temporary.
107 Database caching
108 ----------------
110 To use a database table as your cache backend, first create a cache table in
111 your database by running this command::
113     python manage.py createcachetable [cache_table_name]
115 ...where ``[cache_table_name]`` is the name of the database table to create.
116 (This name can be whatever you want, as long as it's a valid table name that's
117 not already being used in your database.) This command creates a single table
118 in your database that is in the proper format that Django's database-cache
119 system expects.
121 Once you've created that database table, set your ``CACHE_BACKEND`` setting to
122 ``"db://tablename"``, where ``tablename`` is the name of the database table.
123 In this example, the cache table's name is ``my_cache_table``::
125     CACHE_BACKEND = 'db://my_cache_table'
127 Database caching works best if you've got a fast, well-indexed database server.
129 Filesystem caching
130 ------------------
132 To store cached items on a filesystem, use the ``"file://"`` cache type for
133 ``CACHE_BACKEND``. For example, to store cached data in ``/var/tmp/django_cache``,
134 use this setting::
136     CACHE_BACKEND = 'file:///var/tmp/django_cache'
138 Note that there are three forward slashes toward the beginning of that example.
139 The first two are for ``file://``, and the third is the first character of the
140 directory path, ``/var/tmp/django_cache``.
142 The directory path should be absolute -- that is, it should start at the root
143 of your filesystem. It doesn't matter whether you put a slash at the end of the
144 setting.
146 Make sure the directory pointed-to by this setting exists and is readable and
147 writable by the system user under which your Web server runs. Continuing the
148 above example, if your server runs as the user ``apache``, make sure the
149 directory ``/var/tmp/django_cache`` exists and is readable and writable by the
150 user ``apache``.
152 Local-memory caching
153 --------------------
155 If you want the speed advantages of in-memory caching but don't have the
156 capability of running Memcached, consider the local-memory cache backend. This
157 cache is multi-process and thread-safe. To use it, set ``CACHE_BACKEND`` to
158 ``"locmem:///"``. For example::
160     CACHE_BACKEND = 'locmem:///'
162 Dummy caching (for development)
163 -------------------------------
165 Finally, Django comes with a "dummy" cache that doesn't actually cache -- it
166 just implements the cache interface without doing anything.
168 This is useful if you have a production site that uses heavy-duty caching in
169 various places but a development/test environment on which you don't want to
170 cache. As a result, your development environment won't use caching and your
171 production environment still will. To activate dummy caching, set
172 ``CACHE_BACKEND`` like so::
174     CACHE_BACKEND = 'dummy:///'
176 Using a custom cache backend
177 ----------------------------
179 **New in Django development version**
181 While Django includes support for a number of cache backends out-of-the-box,
182 sometimes you will want to use a customised verison or your own backend.  To
183 use an external cache backend with Django, use a Python import path as the
184 scheme portion (the part before the initial colon) of the ``CACHE_BACKEND``
185 URI, like so::
187     CACHE_BACKEND = 'path.to.backend://'
189 If you're building your own backend, you can use the standard cache backends
190 as reference implementations. You'll find the code in the
191 ``django/core/cache/backends/`` directory of the Django source.
193 Note: Without a really compelling reason, like a host that doesn't support the
194 them, you should stick to the cache backends included with Django. They've
195 been really well-tested and are quite easy to use.
197 CACHE_BACKEND arguments
198 -----------------------
200 All caches may take arguments. They're given in query-string style on the
201 ``CACHE_BACKEND`` setting. Valid arguments are:
203     timeout
204         Default timeout, in seconds, to use for the cache. Defaults to 5
205         minutes (300 seconds).
207     max_entries
208         For the simple and database backends, the maximum number of entries
209         allowed in the cache before it is cleaned. Defaults to 300.
211     cull_percentage
212         The percentage of entries that are culled when max_entries is reached.
213         The actual percentage is 1/cull_percentage, so set cull_percentage=3 to
214         cull 1/3 of the entries when max_entries is reached.
216         A value of 0 for cull_percentage means that the entire cache will be
217         dumped when max_entries is reached. This makes culling *much* faster
218         at the expense of more cache misses.
220 In this example, ``timeout`` is set to ``60``::
222     CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=60"
224 In this example, ``timeout`` is ``30`` and ``max_entries`` is ``400``::
226     CACHE_BACKEND = "memcached://127.0.0.1:11211/?timeout=30&max_entries=400"
228 Invalid arguments are silently ignored, as are invalid values of known
229 arguments.
231 The per-site cache
232 ==================
234 **New in Django development version** (previous versions of Django only provided
235 a single ``CacheMiddleware`` instead of the two pieces described below).
237 Once the cache is set up, the simplest way to use caching is to cache your
238 entire site. You'll need to add
239 ``'django.middleware.cache.UpdateCacheMiddleware'`` and
240 ``'django.middleware.cache.FetchFromCacheMiddleware' to your
241 ``MIDDLEWARE_CLASSES`` setting, as in this example::
243     MIDDLEWARE_CLASSES = (
244         'django.middleware.cache.UpdateCacheMiddleware',
245         'django.middleware.common.CommonMiddleware',
246         'django.middleware.cache.FetchFromCacheMiddleware',
247     )
249 .. note::
251     No, that's not a typo: the "update" middleware must be first in the list,
252     and the "fetch" middleware must be last. The details are a bit obscure, but
253     see `Order of MIDDLEWARE_CLASSES`_ below if you'd like the full story.
255 Then, add the following required settings to your Django settings file:
257 * ``CACHE_MIDDLEWARE_SECONDS`` -- The number of seconds each page should be
258   cached.
259 * ``CACHE_MIDDLEWARE_KEY_PREFIX`` -- If the cache is shared across multiple
260   sites using the same Django installation, set this to the name of the site,
261   or some other string that is unique to this Django instance, to prevent key
262   collisions. Use an empty string if you don't care.
264 The cache middleware caches every page that doesn't have GET or POST
265 parameters. Optionally, if the ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting is
266 ``True``, only anonymous requests (i.e., not those made by a logged-in user)
267 will be cached. This is a simple and effective way of disabling caching for any
268 user-specific pages (include Django's admin interface). Note that if you use
269 ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY``, you should make sure you've activated
270 ``AuthenticationMiddleware``.
272 Additionally, the cache middleware automatically sets a few headers in each
273 ``HttpResponse``:
275 * Sets the ``Last-Modified`` header to the current date/time when a fresh
276   (uncached) version of the page is requested.
277 * Sets the ``Expires`` header to the current date/time plus the defined
278   ``CACHE_MIDDLEWARE_SECONDS``.
279 * Sets the ``Cache-Control`` header to give a max age for the page -- again,
280   from the ``CACHE_MIDDLEWARE_SECONDS`` setting.
282 See the `middleware documentation`_ for more on middleware.
284 .. _`middleware documentation`: ../middleware/
286 **New in Django development version**
288 If a view sets its own cache expiry time (i.e. it has a ``max-age`` section in
289 its ``Cache-Control`` header) then the page will be cached until the expiry
290 time, rather than ``CACHE_MIDDLEWARE_SECONDS``. Using the decorators in
291 ``django.views.decorators.cache`` you can easily set a view's expiry time
292 (using the ``cache_control`` decorator) or disable caching for a view (using
293 the ``never_cache`` decorator). See the `using other headers`__ section for
294 more on these decorators.
296 __ `Controlling cache: Using other headers`_
298 The per-view cache
299 ==================
301 A more granular way to use the caching framework is by caching the output of
302 individual views. ``django.views.decorators.cache`` defines a ``cache_page``
303 decorator that will automatically cache the view's response for you. It's easy
304 to use::
306     from django.views.decorators.cache import cache_page
308     def slashdot_this(request):
309         ...
311     slashdot_this = cache_page(slashdot_this, 60 * 15)
313 Or, using Python 2.4's decorator syntax::
315     @cache_page(60 * 15)
316     def slashdot_this(request):
317         ...
319 ``cache_page`` takes a single argument: the cache timeout, in seconds. In the
320 above example, the result of the ``slashdot_this()`` view will be cached for 15
321 minutes.
323 Template fragment caching
324 =========================
326 **New in development version**
328 If you're after even more control, you can also cache template fragments using
329 the ``cache`` template tag. To give your template access to this tag, put
330 ``{% load cache %}`` near the top of your template.
332 The ``{% cache %}`` template tag caches the contents of the block for a given
333 amount of time. It takes at least two arguments: the cache timeout, in seconds,
334 and the name to give the cache fragment. For example::
336     {% load cache %}
337     {% cache 500 sidebar %}
338         .. sidebar ..
339     {% endcache %}
341 Sometimes you might want to cache multiple copies of a fragment depending on
342 some dynamic data that appears inside the fragment. For example, you might want a
343 separate cached copy of the sidebar used in the previous example for every user
344 of your site. Do this by passing additional arguments to the ``{% cache %}``
345 template tag to uniquely identify the cache fragment::
347     {% load cache %}
348     {% cache 500 sidebar request.user.username %}
349         .. sidebar for logged in user ..
350     {% endcache %}
352 It's perfectly fine to specify more than one argument to identify the fragment.
353 Simply pass as many arguments to ``{% cache %}`` as you need.
355 The cache timeout can be a template variable, as long as the template variable
356 resolves to an integer value. For example, if the template variable
357 ``my_timeout`` is set to the value ``600``, then the following two examples are
358 equivalent::
360     {% cache 600 sidebar %} ... {% endcache %}
361     {% cache my_timeout sidebar %} ... {% endcache %}
363 This feature is useful in avoiding repetition in templates. You can set the
364 timeout in a variable, in one place, and just reuse that value.
366 The low-level cache API
367 =======================
369 Sometimes, however, caching an entire rendered page doesn't gain you very much.
370 For example, you may find it's only necessary to cache the result of an
371 intensive database query. In cases like this, you can use the low-level cache
372 API to store objects in the cache with any level of granularity you like.
374 The cache API is simple. The cache module, ``django.core.cache``, exports a
375 ``cache`` object that's automatically created from the ``CACHE_BACKEND``
376 setting::
378     >>> from django.core.cache import cache
380 The basic interface is ``set(key, value, timeout_seconds)`` and ``get(key)``::
382     >>> cache.set('my_key', 'hello, world!', 30)
383     >>> cache.get('my_key')
384     'hello, world!'
386 The ``timeout_seconds`` argument is optional and defaults to the ``timeout``
387 argument in the ``CACHE_BACKEND`` setting (explained above).
389 If the object doesn't exist in the cache, ``cache.get()`` returns ``None``::
391     >>> cache.get('some_other_key')
392     None
394     # Wait 30 seconds for 'my_key' to expire...
396     >>> cache.get('my_key')
397     None
399 get() can take a ``default`` argument::
401     >>> cache.get('my_key', 'has expired')
402     'has expired'
404 **New in Django development version:** To add a key only if it doesn't already
405 exist, use the ``add()`` method. It takes the same parameters as ``set()``, but
406 it will not attempt to update the cache if the key specified is already present::
408     >>> cache.set('add_key', 'Initial value')
409     >>> cache.add('add_key', 'New value')
410     >>> cache.get('add_key')
411     'Initial value'
413 If you need to know whether ``add()`` stored a value in the cache, you can
414 check the return value. It will return ``True`` if the value was stored,
415 ``False`` otherwise.
417 There's also a ``get_many()`` interface that only hits the cache once.
418 ``get_many()`` returns a dictionary with all the keys you asked for that
419 actually exist in the cache (and haven't expired)::
421     >>> cache.set('a', 1)
422     >>> cache.set('b', 2)
423     >>> cache.set('c', 3)
424     >>> cache.get_many(['a', 'b', 'c'])
425     {'a': 1, 'b': 2, 'c': 3}
427 Finally, you can delete keys explicitly with ``delete()``. This is an easy way
428 of clearing the cache for a particular object::
430     >>> cache.delete('a')
432 That's it. The cache has very few restrictions: You can cache any object that
433 can be pickled safely, although keys must be strings.
435 Upstream caches
436 ===============
438 So far, this document has focused on caching your *own* data. But another type
439 of caching is relevant to Web development, too: caching performed by "upstream"
440 caches. These are systems that cache pages for users even before the request
441 reaches your Web site.
443 Here are a few examples of upstream caches:
445     * Your ISP may cache certain pages, so if you requested a page from
446       somedomain.com, your ISP would send you the page without having to access
447       somedomain.com directly.
449     * Your Django Web site may sit behind a Squid Web proxy
450       (http://www.squid-cache.org/) that caches pages for performance. In this
451       case, each request first would be handled by Squid, and it'd only be
452       passed to your application if needed.
454     * Your Web browser caches pages, too. If a Web page sends out the right
455       headers, your browser will use the local (cached) copy for subsequent
456       requests to that page.
458 Upstream caching is a nice efficiency boost, but there's a danger to it:
459 Many Web pages' contents differ based on authentication and a host of other
460 variables, and cache systems that blindly save pages based purely on URLs could
461 expose incorrect or sensitive data to subsequent visitors to those pages.
463 For example, say you operate a Web e-mail system, and the contents of the
464 "inbox" page obviously depend on which user is logged in. If an ISP blindly
465 cached your site, then the first user who logged in through that ISP would have
466 his user-specific inbox page cached for subsequent visitors to the site. That's
467 not cool.
469 Fortunately, HTTP provides a solution to this problem: A set of HTTP headers
470 exist to instruct caching mechanisms to differ their cache contents depending
471 on designated variables, and to tell caching mechanisms not to cache particular
472 pages.
474 Using Vary headers
475 ==================
477 One of these headers is ``Vary``. It defines which request headers a cache
478 mechanism should take into account when building its cache key. For example, if
479 the contents of a Web page depend on a user's language preference, the page is
480 said to "vary on language."
482 By default, Django's cache system creates its cache keys using the requested
483 path -- e.g., ``"/stories/2005/jun/23/bank_robbed/"``. This means every request
484 to that URL will use the same cached version, regardless of user-agent
485 differences such as cookies or language preferences.
487 That's where ``Vary`` comes in.
489 If your Django-powered page outputs different content based on some difference
490 in request headers -- such as a cookie, or language, or user-agent -- you'll
491 need to use the ``Vary`` header to tell caching mechanisms that the page output
492 depends on those things.
494 To do this in Django, use the convenient ``vary_on_headers`` view decorator,
495 like so::
497     from django.views.decorators.vary import vary_on_headers
499     # Python 2.3 syntax.
500     def my_view(request):
501         ...
502     my_view = vary_on_headers(my_view, 'User-Agent')
504     # Python 2.4 decorator syntax.
505     @vary_on_headers('User-Agent')
506     def my_view(request):
507         ...
509 In this case, a caching mechanism (such as Django's own cache middleware) will
510 cache a separate version of the page for each unique user-agent.
512 The advantage to using the ``vary_on_headers`` decorator rather than manually
513 setting the ``Vary`` header (using something like
514 ``response['Vary'] = 'user-agent'``) is that the decorator adds to the ``Vary``
515 header (which may already exist) rather than setting it from scratch.
517 You can pass multiple headers to ``vary_on_headers()``::
519     @vary_on_headers('User-Agent', 'Cookie')
520     def my_view(request):
521         ...
523 Because varying on cookie is such a common case, there's a ``vary_on_cookie``
524 decorator. These two views are equivalent::
526     @vary_on_cookie
527     def my_view(request):
528         ...
530     @vary_on_headers('Cookie')
531     def my_view(request):
532         ...
534 Also note that the headers you pass to ``vary_on_headers`` are not case
535 sensitive. ``"User-Agent"`` is the same thing as ``"user-agent"``.
537 You can also use a helper function, ``django.utils.cache.patch_vary_headers``,
538 directly::
540     from django.utils.cache import patch_vary_headers
541     def my_view(request):
542         ...
543         response = render_to_response('template_name', context)
544         patch_vary_headers(response, ['Cookie'])
545         return response
547 ``patch_vary_headers`` takes an ``HttpResponse`` instance as its first argument
548 and a list/tuple of header names as its second argument.
550 For more on Vary headers, see the `official Vary spec`_.
552 .. _`official Vary spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
554 Controlling cache: Using other headers
555 ======================================
557 Another problem with caching is the privacy of data and the question of where
558 data should be stored in a cascade of caches.
560 A user usually faces two kinds of caches: his own browser cache (a private
561 cache) and his provider's cache (a public cache). A public cache is used by
562 multiple users and controlled by someone else. This poses problems with
563 sensitive data: You don't want, say, your banking-account number stored in a
564 public cache. So Web applications need a way to tell caches which data is
565 private and which is public.
567 The solution is to indicate a page's cache should be "private." To do this in
568 Django, use the ``cache_control`` view decorator. Example::
570     from django.views.decorators.cache import cache_control
571     @cache_control(private=True)
572     def my_view(request):
573         ...
575 This decorator takes care of sending out the appropriate HTTP header behind the
576 scenes.
578 There are a few other ways to control cache parameters. For example, HTTP
579 allows applications to do the following:
581     * Define the maximum time a page should be cached.
582     * Specify whether a cache should always check for newer versions, only
583       delivering the cached content when there are no changes. (Some caches
584       might deliver cached content even if the server page changed -- simply
585       because the cache copy isn't yet expired.)
587 In Django, use the ``cache_control`` view decorator to specify these cache
588 parameters. In this example, ``cache_control`` tells caches to revalidate the
589 cache on every access and to store cached versions for, at most, 3600 seconds::
591     from django.views.decorators.cache import cache_control
592     @cache_control(must_revalidate=True, max_age=3600)
593     def my_view(request):
594         ...
596 Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
597 Here's a full list:
599     * ``public=True``
600     * ``private=True``
601     * ``no_cache=True``
602     * ``no_transform=True``
603     * ``must_revalidate=True``
604     * ``proxy_revalidate=True``
605     * ``max_age=num_seconds``
606     * ``s_maxage=num_seconds``
608 For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
610 (Note that the caching middleware already sets the cache header's max-age with
611 the value of the ``CACHE_MIDDLEWARE_SETTINGS`` setting. If you use a custom
612 ``max_age`` in a ``cache_control`` decorator, the decorator will take
613 precedence, and the header values will be merged correctly.)
615 If you want to use headers to disable caching altogether,
616 ``django.views.decorators.cache.never_cache`` is a view decorator that adds
617 headers to ensure the response won't be cached by browsers or other caches. Example::
619     from django.views.decorators.cache import never_cache
620     @never_cache
621     def myview(request):
622         ...
624 .. _`Cache-Control spec`: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
626 Other optimizations
627 ===================
629 Django comes with a few other pieces of middleware that can help optimize your
630 apps' performance:
632     * ``django.middleware.http.ConditionalGetMiddleware`` adds support for
633       conditional GET. This makes use of ``ETag`` and ``Last-Modified``
634       headers.
636     * ``django.middleware.gzip.GZipMiddleware`` compresses content for browsers
637       that understand gzip compression (all modern browsers).
639 Order of MIDDLEWARE_CLASSES
640 ===========================
642 If you use caching middleware, it's important to put each half in the right
643 place within the ``MIDDLEWARE_CLASSES`` setting. That's because the cache
644 middleware needs to know which headers by which to vary the cache storage.
645 Middleware always adds something to the ``Vary`` response header when it can.
647 ``UpdateCacheMiddleware`` runs during the response phase, where middleware is
648 run in reverse order, so an item at the top of the list runs *last* during the
649 response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
650 appears *before* any other middleware that might add something to the ``Vary``
651 header. The following middleware modules do so:
653     * ``SessionMiddleware`` adds ``Cookie``
654     * ``GZipMiddleware`` adds ``Accept-Encoding``
655     * ``LocaleMiddleware`` adds ``Accept-Language``
656     
657 ``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
658 where middleware is applied first-to-last, so an item at the top of the list
659 runs *first* during the request phase. The ``FetchFromCacheMiddleware`` also
660 needs to run after other middleware updates the ``Vary`` header, so
661 ``FetchFromCacheMiddleware`` must be *after* any item that does so.