Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 65530c6176058f9b54858c3b4f6385e6 > files > 918

python-django-doc-1.8.19-1.mga6.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" lang="">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Django’s cache framework &#8212; Django 1.8.19 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.8.19',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="top" title="Django 1.8.19 documentation" href="../contents.html" />
    <link rel="up" title="Using Django" href="index.html" />
    <link rel="next" title="Conditional View Processing" href="conditional-view-processing.html" />
    <link rel="prev" title="Customizing authentication in Django" href="auth/customizing.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body role="document">

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.8.19 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="auth/customizing.html" title="Customizing authentication in Django">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="conditional-view-processing.html" title="Conditional View Processing">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-cache">
            
  <div class="section" id="s-django-s-cache-framework">
<span id="django-s-cache-framework"></span><h1>Django&#8217;s cache framework<a class="headerlink" href="#django-s-cache-framework" title="Permalink to this headline">¶</a></h1>
<p>A fundamental trade-off in dynamic Web sites is, well, they&#8217;re dynamic. Each
time a user requests a page, the Web server makes all sorts of calculations &#8211;
from database queries to template rendering to business logic &#8211; to create the
page that your site&#8217;s visitor sees. This is a lot more expensive, from a
processing-overhead perspective, than your standard
read-a-file-off-the-filesystem server arrangement.</p>
<p>For most Web applications, this overhead isn&#8217;t a big deal. Most Web
applications aren&#8217;t <code class="docutils literal"><span class="pre">washingtonpost.com</span></code> or <code class="docutils literal"><span class="pre">slashdot.org</span></code>; they&#8217;re simply
small- to medium-sized sites with so-so traffic. But for medium- to
high-traffic sites, it&#8217;s essential to cut as much overhead as possible.</p>
<p>That&#8217;s where caching comes in.</p>
<p>To cache something is to save the result of an expensive calculation so that
you don&#8217;t have to perform the calculation next time. Here&#8217;s some pseudocode
explaining how this would work for a dynamically generated Web page:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">given</span> <span class="n">a</span> <span class="n">URL</span><span class="p">,</span> <span class="k">try</span> <span class="n">finding</span> <span class="n">that</span> <span class="n">page</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span>
<span class="k">if</span> <span class="n">the</span> <span class="n">page</span> <span class="ow">is</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">the</span> <span class="n">cached</span> <span class="n">page</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">generate</span> <span class="n">the</span> <span class="n">page</span>
    <span class="n">save</span> <span class="n">the</span> <span class="n">generated</span> <span class="n">page</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span> <span class="p">(</span><span class="k">for</span> <span class="nb">next</span> <span class="n">time</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">the</span> <span class="n">generated</span> <span class="n">page</span>
</pre></div>
</div>
<p>Django comes with a robust cache system that lets you save dynamic pages so
they don&#8217;t have to be calculated for each request. For convenience, Django
offers different levels of cache granularity: You can cache the output of
specific views, you can cache only the pieces that are difficult to produce,
or you can cache your entire site.</p>
<p>Django also works well with &#8220;downstream&#8221; caches, such as <a class="reference external" href="http://www.squid-cache.org">Squid</a> and browser-based caches. These are the types of
caches that you don&#8217;t directly control but to which you can provide hints (via
HTTP headers) about which parts of your site should be cached, and how.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="../misc/design-philosophies.html#cache-design-philosophy"><span class="std std-ref">Cache Framework design philosophy</span></a>
explains a few of the design decisions of the framework.</p>
</div>
<div class="section" id="s-setting-up-the-cache">
<span id="s-id1"></span><span id="setting-up-the-cache"></span><span id="id1"></span><h2>Setting up the cache<a class="headerlink" href="#setting-up-the-cache" title="Permalink to this headline">¶</a></h2>
<p>The cache system requires a small amount of setup. Namely, you have to tell it
where your cached data should live &#8211; whether in a database, on the filesystem
or directly in memory. This is an important decision that affects your cache&#8217;s
performance; yes, some cache types are faster than others.</p>
<p>Your cache preference goes in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting in your
settings file. Here&#8217;s an explanation of all available values for
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a>.</p>
<div class="section" id="s-memcached">
<span id="s-id2"></span><span id="memcached"></span><span id="id2"></span><h3>Memcached<a class="headerlink" href="#memcached" title="Permalink to this headline">¶</a></h3>
<p>The fastest, most efficient type of cache supported natively by Django,
<a class="reference external" href="http://memcached.org/">Memcached</a> is an entirely memory-based cache server, originally developed
to handle high loads at LiveJournal.com and subsequently open-sourced by
Danga Interactive. It is used by sites such as Facebook and Wikipedia to
reduce database access and dramatically increase site performance.</p>
<p>Memcached runs as a daemon and is allotted a specified amount of RAM. All it
does is provide a fast interface for adding, retrieving and deleting data in
the cache. All data is stored directly in memory, so there&#8217;s no overhead of
database or filesystem usage.</p>
<p>After installing Memcached itself, you&#8217;ll need to install a Memcached
binding. There are several Python Memcached bindings available; the
two most common are <a class="reference external" href="https://pypi.python.org/pypi/python-memcached">python-memcached</a> and <a class="reference external" href="https://pypi.python.org/pypi/pylibmc">pylibmc</a>.</p>
<p>To use Memcached with Django:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal"><span class="pre">django.core.cache.backends.memcached.MemcachedCache</span></code> or
<code class="docutils literal"><span class="pre">django.core.cache.backends.memcached.PyLibMCCache</span></code> (depending
on your chosen memcached binding)</li>
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a> to <code class="docutils literal"><span class="pre">ip:port</span></code> values,
where <code class="docutils literal"><span class="pre">ip</span></code> is the IP address of the Memcached daemon and <code class="docutils literal"><span class="pre">port</span></code> is the
port on which Memcached is running, or to a <code class="docutils literal"><span class="pre">unix:path</span></code> value, where
<code class="docutils literal"><span class="pre">path</span></code> is the path to a Memcached Unix socket file.</li>
</ul>
<p>In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
the <code class="docutils literal"><span class="pre">python-memcached</span></code> binding:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.MemcachedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;127.0.0.1:11211&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this example, Memcached is available through a local Unix socket file
<code class="file docutils literal"><span class="pre">/tmp/memcached.sock</span></code> using the <code class="docutils literal"><span class="pre">python-memcached</span></code> binding:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.MemcachedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;unix:/tmp/memcached.sock&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>When using the <code class="docutils literal"><span class="pre">pylibmc</span></code> binding, do not include the <code class="docutils literal"><span class="pre">unix:/</span></code> prefix:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyLibMCCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;/tmp/memcached.sock&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>One excellent feature of Memcached is its ability to share a cache over
multiple servers. This means you can run Memcached daemons on multiple
machines, and the program will treat the group of machines as a <em>single</em>
cache, without the need to duplicate cache values on each machine. To take
advantage of this feature, include all server addresses in
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a>, either separated by semicolons or as
a list.</p>
<p>In this example, the cache is shared over Memcached instances running on IP
address 172.19.26.240 and 172.19.26.242, both on port 11211:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.MemcachedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="p">[</span>
            <span class="s1">&#39;172.19.26.240:11211&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.242:11211&#39;</span><span class="p">,</span>
        <span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the following example, the cache is shared over Memcached instances running
on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
172.19.26.244 (port 11213):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.MemcachedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="p">[</span>
            <span class="s1">&#39;172.19.26.240:11211&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.242:11212&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.244:11213&#39;</span><span class="p">,</span>
        <span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>A final point about Memcached is that memory-based caching has a
disadvantage: because the cached data is stored in memory, the data will be
lost if your server crashes. Clearly, memory isn&#8217;t intended for permanent data
storage, so don&#8217;t rely on memory-based caching as your only data storage.
Without a doubt, <em>none</em> of the Django caching backends should be used for
permanent storage &#8211; they&#8217;re all intended to be solutions for caching, not
storage &#8211; but we point this out here because memory-based caching is
particularly temporary.</p>
</div>
<div class="section" id="s-database-caching">
<span id="s-id4"></span><span id="database-caching"></span><span id="id4"></span><h3>Database caching<a class="headerlink" href="#database-caching" title="Permalink to this headline">¶</a></h3>
<p>Django can store its cached data in your database. This works best if you&#8217;ve
got a fast, well-indexed database server.</p>
<p>To use a database table as your cache backend:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal"><span class="pre">django.core.cache.backends.db.DatabaseCache</span></code></li>
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a> to <code class="docutils literal"><span class="pre">tablename</span></code>, the name of the
database table. This name can be whatever you want, as long as it&#8217;s a valid
table name that&#8217;s not already being used in your database.</li>
</ul>
<p>In this example, the cache table&#8217;s name is <code class="docutils literal"><span class="pre">my_cache_table</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.db.DatabaseCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;my_cache_table&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="section" id="s-creating-the-cache-table">
<span id="creating-the-cache-table"></span><h4>Creating the cache table<a class="headerlink" href="#creating-the-cache-table" title="Permalink to this headline">¶</a></h4>
<p>Before using the database cache, you must create the cache table with this
command:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">createcachetable</span>
</pre></div>
</div>
<p>This creates a table in your database that is in the proper format that
Django&#8217;s database-cache system expects. The name of the table is taken from
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a>.</p>
<p>If you are using multiple database caches, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal"><span class="pre">createcachetable</span></code></a> creates
one table for each cache.</p>
<p>If you are using multiple databases, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal"><span class="pre">createcachetable</span></code></a> observes the
<code class="docutils literal"><span class="pre">allow_migrate()</span></code> method of your database routers (see below).</p>
<p>Like <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></code></a>, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal"><span class="pre">createcachetable</span></code></a> won&#8217;t touch an existing
table. It will only create missing tables.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>Before Django 1.7, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal"><span class="pre">createcachetable</span></code></a> created one table at a time.
You had to pass the name of the table you wanted to create, and if you were
using multiple databases, you had to use the <a class="reference internal" href="../ref/django-admin.html#django-admin-option---database"><code class="xref std std-djadminopt docutils literal"><span class="pre">--database</span></code></a>
option. For backwards compatibility, this is still possible.</p>
</div>
</div>
<div class="section" id="s-multiple-databases">
<span id="multiple-databases"></span><h4>Multiple databases<a class="headerlink" href="#multiple-databases" title="Permalink to this headline">¶</a></h4>
<p>If you use database caching with multiple databases, you&#8217;ll also need
to set up routing instructions for your database cache table. For the
purposes of routing, the database cache table appears as a model named
<code class="docutils literal"><span class="pre">CacheEntry</span></code>, in an application named <code class="docutils literal"><span class="pre">django_cache</span></code>. This model
won&#8217;t appear in the models cache, but the model details can be used
for routing purposes.</p>
<p>For example, the following router would direct all cache read
operations to <code class="docutils literal"><span class="pre">cache_replica</span></code>, and all write operations to
<code class="docutils literal"><span class="pre">cache_primary</span></code>. The cache table will only be synchronized onto
<code class="docutils literal"><span class="pre">cache_primary</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CacheRouter</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A router to control all database cache operations&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">db_for_read</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;All cache read operations go to the replica&quot;</span>
        <span class="k">if</span> <span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;cache_replica&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">db_for_write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;All cache write operations go to primary&quot;</span>
        <span class="k">if</span> <span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;cache_primary&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">allow_migrate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">db</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">model_name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;Only install the cache model on primary&quot;</span>
        <span class="k">if</span> <span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">db</span> <span class="o">==</span> <span class="s1">&#39;cache_primary&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>
</pre></div>
</div>
<p>If you don&#8217;t specify routing directions for the database cache model,
the cache backend will use the <code class="docutils literal"><span class="pre">default</span></code> database.</p>
<p>Of course, if you don&#8217;t use the database cache backend, you don&#8217;t need
to worry about providing routing instructions for the database cache
model.</p>
</div>
</div>
<div class="section" id="s-filesystem-caching">
<span id="filesystem-caching"></span><h3>Filesystem caching<a class="headerlink" href="#filesystem-caching" title="Permalink to this headline">¶</a></h3>
<p>The file-based backend serializes and stores each cache value as a separate
file. To use this backend set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal"><span class="pre">&quot;django.core.cache.backends.filebased.FileBasedCache&quot;</span></code> and
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a> to a suitable directory. For example,
to store cached data in <code class="docutils literal"><span class="pre">/var/tmp/django_cache</span></code>, use this setting:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;/var/tmp/django_cache&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If you&#8217;re on Windows, put the drive letter at the beginning of the path,
like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;c:/foo/bar&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The directory path should be absolute &#8211; that is, it should start at the root
of your filesystem. It doesn&#8217;t matter whether you put a slash at the end of the
setting.</p>
<p>Make sure the directory pointed-to by this setting exists and is readable and
writable by the system user under which your Web server runs. Continuing the
above example, if your server runs as the user <code class="docutils literal"><span class="pre">apache</span></code>, make sure the
directory <code class="docutils literal"><span class="pre">/var/tmp/django_cache</span></code> exists and is readable and writable by the
user <code class="docutils literal"><span class="pre">apache</span></code>.</p>
</div>
<div class="section" id="s-local-memory-caching">
<span id="local-memory-caching"></span><h3>Local-memory caching<a class="headerlink" href="#local-memory-caching" title="Permalink to this headline">¶</a></h3>
<p>This is the default cache if another is not specified in your settings file. If
you want the speed advantages of in-memory caching but don&#8217;t have the capability
of running Memcached, consider the local-memory cache backend. This cache is
per-process (see below) and thread-safe. To use it, set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to <code class="docutils literal"><span class="pre">&quot;django.core.cache.backends.locmem.LocMemCache&quot;</span></code>. For
example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.locmem.LocMemCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;unique-snowflake&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The cache <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a> is used to identify individual
memory stores. If you only have one <code class="docutils literal"><span class="pre">locmem</span></code> cache, you can omit the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal"><span class="pre">LOCATION</span></code></a>; however, if you have more than one local
memory cache, you will need to assign a name to at least one of them in
order to keep them separate.</p>
<p>Note that each process will have its own private cache instance, which means no
cross-process caching is possible. This obviously also means the local memory
cache isn&#8217;t particularly memory-efficient, so it&#8217;s probably not a good choice
for production environments. It&#8217;s nice for development.</p>
</div>
<div class="section" id="s-dummy-caching-for-development">
<span id="dummy-caching-for-development"></span><h3>Dummy caching (for development)<a class="headerlink" href="#dummy-caching-for-development" title="Permalink to this headline">¶</a></h3>
<p>Finally, Django comes with a &#8220;dummy&#8221; cache that doesn&#8217;t actually cache &#8211; it
just implements the cache interface without doing anything.</p>
<p>This is useful if you have a production site that uses heavy-duty caching in
various places but a development/test environment where you don&#8217;t want to cache
and don&#8217;t want to have to change your code to special-case the latter. To
activate dummy caching, set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> like so:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.dummy.DummyCache&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-a-custom-cache-backend">
<span id="using-a-custom-cache-backend"></span><h3>Using a custom cache backend<a class="headerlink" href="#using-a-custom-cache-backend" title="Permalink to this headline">¶</a></h3>
<p>While Django includes support for a number of cache backends out-of-the-box,
sometimes you might want to use a customized cache backend. To use an external
cache backend with Django, use the Python import path as the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> of the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting, like so:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;path.to.backend&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If you&#8217;re building your own backend, you can use the standard cache backends
as reference implementations. You&#8217;ll find the code in the
<code class="docutils literal"><span class="pre">django/core/cache/backends/</span></code> directory of the Django source.</p>
<p>Note: Without a really compelling reason, such as a host that doesn&#8217;t support
them, you should stick to the cache backends included with Django. They&#8217;ve
been well-tested and are easy to use.</p>
</div>
<div class="section" id="s-cache-arguments">
<span id="cache-arguments"></span><h3>Cache arguments<a class="headerlink" href="#cache-arguments" title="Permalink to this headline">¶</a></h3>
<p>Each cache backend can be given additional arguments to control caching
behavior. These arguments are provided as additional keys in the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting. Valid arguments are as follows:</p>
<ul>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-TIMEOUT"><code class="xref std std-setting docutils literal"><span class="pre">TIMEOUT</span></code></a>: The default timeout, in
seconds, to use for the cache. This argument defaults to <code class="docutils literal"><span class="pre">300</span></code> seconds (5 minutes).</p>
<div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>You can set <code class="docutils literal"><span class="pre">TIMEOUT</span></code> to <code class="docutils literal"><span class="pre">None</span></code> so that, by default, cache keys never
expire. A value of <code class="docutils literal"><span class="pre">0</span></code> causes keys to immediately expire (effectively
&#8220;don&#8217;t cache&#8221;).</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-OPTIONS"><code class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></code></a>: Any options that should be
passed to the cache backend. The list of valid options will vary
with each backend, and cache backends backed by a third-party library
will pass their options directly to the underlying cache library.</p>
<p>Cache backends that implement their own culling strategy (i.e.,
the <code class="docutils literal"><span class="pre">locmem</span></code>, <code class="docutils literal"><span class="pre">filesystem</span></code> and <code class="docutils literal"><span class="pre">database</span></code> backends) will
honor the following options:</p>
<ul>
<li><p class="first"><code class="docutils literal"><span class="pre">MAX_ENTRIES</span></code>: The maximum number of entries allowed in
the cache before old values are deleted. This argument
defaults to <code class="docutils literal"><span class="pre">300</span></code>.</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">CULL_FREQUENCY</span></code>: The fraction of entries that are culled
when <code class="docutils literal"><span class="pre">MAX_ENTRIES</span></code> is reached. The actual ratio is
<code class="docutils literal"><span class="pre">1</span> <span class="pre">/</span> <span class="pre">CULL_FREQUENCY</span></code>, so set <code class="docutils literal"><span class="pre">CULL_FREQUENCY</span></code> to <code class="docutils literal"><span class="pre">2</span></code> to
cull half the entries when <code class="docutils literal"><span class="pre">MAX_ENTRIES</span></code> is reached. This argument
should be an integer and defaults to <code class="docutils literal"><span class="pre">3</span></code>.</p>
<p>A value of <code class="docutils literal"><span class="pre">0</span></code> for <code class="docutils literal"><span class="pre">CULL_FREQUENCY</span></code> means that the
entire cache will be dumped when <code class="docutils literal"><span class="pre">MAX_ENTRIES</span></code> is reached.
On some backends (<code class="docutils literal"><span class="pre">database</span></code> in particular) this makes culling <em>much</em>
faster at the expense of more cache misses.</p>
</li>
</ul>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">KEY_PREFIX</span></code></a>: A string that will be
automatically included (prepended by default) to all cache keys
used by the Django server.</p>
<p>See the <a class="reference internal" href="#cache-key-prefixing"><span class="std std-ref">cache documentation</span></a> for
more information.</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-VERSION"><code class="xref std std-setting docutils literal"><span class="pre">VERSION</span></code></a>: The default version number
for cache keys generated by the Django server.</p>
<p>See the <a class="reference internal" href="#cache-versioning"><span class="std std-ref">cache documentation</span></a> for more
information.</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_FUNCTION"><code class="xref std std-setting docutils literal"><span class="pre">KEY_FUNCTION</span></code></a>
A string containing a dotted path to a function that defines how
to compose a prefix, version and key into a final cache key.</p>
<p>See the <a class="reference internal" href="#cache-key-transformation"><span class="std std-ref">cache documentation</span></a>
for more information.</p>
</li>
</ul>
<p>In this example, a filesystem backend is being configured with a timeout
of 60 seconds, and a maximum capacity of 1000 items:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;/var/tmp/django_cache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;TIMEOUT&#39;</span><span class="p">:</span> <span class="mi">60</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;MAX_ENTRIES&#39;</span><span class="p">:</span> <span class="mi">1000</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Invalid arguments are silently ignored, as are invalid values of known
arguments.</p>
</div>
</div>
<div class="section" id="s-the-per-site-cache">
<span id="s-id5"></span><span id="the-per-site-cache"></span><span id="id5"></span><h2>The per-site cache<a class="headerlink" href="#the-per-site-cache" title="Permalink to this headline">¶</a></h2>
<p>Once the cache is set up, the simplest way to use caching is to cache your
entire site. You&#8217;ll need to add
<code class="docutils literal"><span class="pre">'django.middleware.cache.UpdateCacheMiddleware'</span></code> and
<code class="docutils literal"><span class="pre">'django.middleware.cache.FetchFromCacheMiddleware'</span></code> to your
<a class="reference internal" href="../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> setting, as in this example:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">MIDDLEWARE_CLASSES</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s1">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.common.CommonMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">No, that&#8217;s not a typo: the &#8220;update&#8221; middleware must be first in the list,
and the &#8220;fetch&#8221; middleware must be last. The details are a bit obscure, but
see <a class="reference internal" href="#order-of-middleware-classes">Order of MIDDLEWARE_CLASSES</a> below if you&#8217;d like the full story.</p>
</div>
<p>Then, add the following required settings to your Django settings file:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_ALIAS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_ALIAS</span></code></a> &#8211; The cache alias to use for storage.</li>
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> &#8211; The number of seconds each page should
be cached.</li>
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_KEY_PREFIX</span></code></a> &#8211; If the cache is shared across
multiple sites using the same Django installation, set this to the name of
the site, or some other string that is unique to this Django instance, to
prevent key collisions. Use an empty string if you don&#8217;t care.</li>
</ul>
<p><code class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></code> caches GET and HEAD responses with status 200,
where the request and response headers allow. Responses to requests for the same
URL with different query parameters are considered to be unique pages and are
cached separately. This middleware expects that a HEAD request is answered with
the same response headers as the corresponding GET request; in which case it can
return a cached GET response for HEAD request.</p>
<p>Additionally, <code class="docutils literal"><span class="pre">UpdateCacheMiddleware</span></code> automatically sets a few headers in each
<a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a>:</p>
<ul class="simple">
<li>Sets the <code class="docutils literal"><span class="pre">Last-Modified</span></code> header to the current date/time when a fresh
(not cached) version of the page is requested.</li>
<li>Sets the <code class="docutils literal"><span class="pre">Expires</span></code> header to the current date/time plus the defined
<a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a>.</li>
<li>Sets the <code class="docutils literal"><span class="pre">Cache-Control</span></code> header to give a max age for the page &#8211;
again, from the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> setting.</li>
</ul>
<p>See <a class="reference internal" href="http/middleware.html"><span class="doc">Middleware</span></a> for more on middleware.</p>
<p>If a view sets its own cache expiry time (i.e. it has a <code class="docutils literal"><span class="pre">max-age</span></code> section in
its <code class="docutils literal"><span class="pre">Cache-Control</span></code> header) then the page will be cached until the expiry
time, rather than <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a>. Using the decorators in
<code class="docutils literal"><span class="pre">django.views.decorators.cache</span></code> you can easily set a view&#8217;s expiry time
(using the <code class="docutils literal"><span class="pre">cache_control</span></code> decorator) or disable caching for a view (using
the <code class="docutils literal"><span class="pre">never_cache</span></code> decorator). See the <a class="reference internal" href="#controlling-cache-using-other-headers">using other headers</a> section for
more on these decorators.</p>
<p id="i18n-cache-key">If <a class="reference internal" href="../ref/settings.html#std:setting-USE_I18N"><code class="xref std std-setting docutils literal"><span class="pre">USE_I18N</span></code></a> is set to <code class="docutils literal"><span class="pre">True</span></code> then the generated cache key will
include the name of the active <a class="reference internal" href="i18n/index.html#term-language-code"><span class="xref std std-term">language</span></a> &#8211; see also
<a class="reference internal" href="i18n/translation.html#how-django-discovers-language-preference"><span class="std std-ref">How Django discovers language preference</span></a>). This allows you to easily
cache multilingual sites without having to create the cache key yourself.</p>
<p>Cache keys also include the active <a class="reference internal" href="i18n/index.html#term-language-code"><span class="xref std std-term">language</span></a> when
<a class="reference internal" href="../ref/settings.html#std:setting-USE_L10N"><code class="xref std std-setting docutils literal"><span class="pre">USE_L10N</span></code></a> is set to <code class="docutils literal"><span class="pre">True</span></code> and the <a class="reference internal" href="i18n/timezones.html#default-current-time-zone"><span class="std std-ref">current time zone</span></a> when <a class="reference internal" href="../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></code></a> is set to <code class="docutils literal"><span class="pre">True</span></code>.</p>
</div>
<div class="section" id="s-the-per-view-cache">
<span id="the-per-view-cache"></span><h2>The per-view cache<a class="headerlink" href="#the-per-view-cache" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="django.views.decorators.cache.cache_page">
<code class="descclassname">django.views.decorators.cache.</code><code class="descname">cache_page</code>()<a class="headerlink" href="#django.views.decorators.cache.cache_page" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A more granular way to use the caching framework is by caching the output of
individual views. <code class="docutils literal"><span class="pre">django.views.decorators.cache</span></code> defines a <code class="docutils literal"><span class="pre">cache_page</span></code>
decorator that will automatically cache the view&#8217;s response for you. It&#8217;s easy
to use:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="k">import</span> <span class="n">cache_page</span>

<span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">cache_page</span></code> takes a single argument: the cache timeout, in seconds. In the
above example, the result of the <code class="docutils literal"><span class="pre">my_view()</span></code> view will be cached for 15
minutes. (Note that we&#8217;ve written it as <code class="docutils literal"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></code> for the purpose of
readability. <code class="docutils literal"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></code> will be evaluated to <code class="docutils literal"><span class="pre">900</span></code> &#8211; that is, 15 minutes
multiplied by 60 seconds per minute.)</p>
<p>The per-view cache, like the per-site cache, is keyed off of the URL. If
multiple URLs point at the same view, each URL will be cached separately.
Continuing the <code class="docutils literal"><span class="pre">my_view</span></code> example, if your URLconf looks like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="s1">r&#39;^foo/([0-9]{1,2})/$&#39;</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>then requests to <code class="docutils literal"><span class="pre">/foo/1/</span></code> and <code class="docutils literal"><span class="pre">/foo/23/</span></code> will be cached separately, as
you may expect. But once a particular URL (e.g., <code class="docutils literal"><span class="pre">/foo/23/</span></code>) has been
requested, subsequent requests to that URL will use the cache.</p>
<p><code class="docutils literal"><span class="pre">cache_page</span></code> can also take an optional keyword argument, <code class="docutils literal"><span class="pre">cache</span></code>,
which directs the decorator to use a specific cache (from your
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting) when caching view results. By default, the
<code class="docutils literal"><span class="pre">default</span></code> cache will be used, but you can specify any cache you
want:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">,</span> <span class="n">cache</span><span class="o">=</span><span class="s2">&quot;special_cache&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>You can also override the cache prefix on a per-view basis. <code class="docutils literal"><span class="pre">cache_page</span></code>
takes an optional keyword argument, <code class="docutils literal"><span class="pre">key_prefix</span></code>,
which works in the same way as the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_KEY_PREFIX</span></code></a>
setting for the middleware.  It can be used like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">,</span> <span class="n">key_prefix</span><span class="o">=</span><span class="s2">&quot;site1&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">key_prefix</span></code> and <code class="docutils literal"><span class="pre">cache</span></code> arguments may be specified together. The
<code class="docutils literal"><span class="pre">key_prefix</span></code> argument and the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">KEY_PREFIX</span></code></a>
specified under <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> will be concatenated.</p>
<div class="section" id="s-specifying-per-view-cache-in-the-urlconf">
<span id="specifying-per-view-cache-in-the-urlconf"></span><h3>Specifying per-view cache in the URLconf<a class="headerlink" href="#specifying-per-view-cache-in-the-urlconf" title="Permalink to this headline">¶</a></h3>
<p>The examples in the previous section have hard-coded the fact that the view is
cached, because <code class="docutils literal"><span class="pre">cache_page</span></code> alters the <code class="docutils literal"><span class="pre">my_view</span></code> function in place. This
approach couples your view to the cache system, which is not ideal for several
reasons. For instance, you might want to reuse the view functions on another,
cache-less site, or you might want to distribute the views to people who might
want to use them without being cached. The solution to these problems is to
specify the per-view cache in the URLconf rather than next to the view functions
themselves.</p>
<p>Doing so is easy: simply wrap the view function with <code class="docutils literal"><span class="pre">cache_page</span></code> when you
refer to it in the URLconf. Here&#8217;s the old URLconf from earlier:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="s1">r&#39;^foo/([0-9]{1,2})/$&#39;</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>Here&#8217;s the same thing, with <code class="docutils literal"><span class="pre">my_view</span></code> wrapped in <code class="docutils literal"><span class="pre">cache_page</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="k">import</span> <span class="n">cache_page</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="s1">r&#39;^foo/([0-9]{1,2})/$&#39;</span><span class="p">,</span> <span class="n">cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">)(</span><span class="n">my_view</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-template-fragment-caching">
<span id="s-std:templatetag-cache"></span><span id="template-fragment-caching"></span><span id="std:templatetag-cache"></span><h2>Template fragment caching<a class="headerlink" href="#template-fragment-caching" title="Permalink to this headline">¶</a></h2>
<p>If you&#8217;re after even more control, you can also cache template fragments using
the <code class="docutils literal"><span class="pre">cache</span></code> template tag. To give your template access to this tag, put
<code class="docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">cache</span> <span class="pre">%}</span></code> near the top of your template.</p>
<p>The <code class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></code> template tag caches the contents of the block for a given
amount of time. It takes at least two arguments: the cache timeout, in seconds,
and the name to give the cache fragment. The name will be taken as is, do not
use a variable. For example:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="m">500</span> <span class="nv">sidebar</span> <span class="cp">%}</span>
    .. sidebar ..
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Sometimes you might want to cache multiple copies of a fragment depending on
some dynamic data that appears inside the fragment. For example, you might want a
separate cached copy of the sidebar used in the previous example for every user
of your site. Do this by passing additional arguments to the <code class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></code>
template tag to uniquely identify the cache fragment:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="m">500</span> <span class="nv">sidebar</span> <span class="nv">request.user.username</span> <span class="cp">%}</span>
    .. sidebar for logged in user ..
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>It&#8217;s perfectly fine to specify more than one argument to identify the fragment.
Simply pass as many arguments to <code class="docutils literal"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></code> as you need.</p>
<p>If <a class="reference internal" href="../ref/settings.html#std:setting-USE_I18N"><code class="xref std std-setting docutils literal"><span class="pre">USE_I18N</span></code></a> is set to <code class="docutils literal"><span class="pre">True</span></code> the per-site middleware cache will
<a class="reference internal" href="#i18n-cache-key"><span class="std std-ref">respect the active language</span></a>. For the <code class="docutils literal"><span class="pre">cache</span></code> template
tag you could use one of the
<a class="reference internal" href="i18n/translation.html#template-translation-vars"><span class="std std-ref">translation-specific variables</span></a> available in
templates to achieve the same result:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">i18n</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">get_current_language</span> <span class="k">as</span> <span class="nv">LANGUAGE_CODE</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">cache</span> <span class="m">600</span> <span class="nv">welcome</span> <span class="nv">LANGUAGE_CODE</span> <span class="cp">%}</span>
    <span class="cp">{%</span> <span class="k">trans</span> <span class="s2">&quot;Welcome to example.com&quot;</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>The cache timeout can be a template variable, as long as the template variable
resolves to an integer value. For example, if the template variable
<code class="docutils literal"><span class="pre">my_timeout</span></code> is set to the value <code class="docutils literal"><span class="pre">600</span></code>, then the following two examples are
equivalent:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">cache</span> <span class="m">600</span> <span class="nv">sidebar</span> <span class="cp">%}</span> ... <span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="nv">my_timeout</span> <span class="nv">sidebar</span> <span class="cp">%}</span> ... <span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>This feature is useful in avoiding repetition in templates. You can set the
timeout in a variable, in one place, and just reuse that value.</p>
<div class="versionadded">
<span class="title">New in Django 1.7:</span> <p>By default, the cache tag will try to use the cache called
&#8220;template_fragments&#8221;. If no such cache exists, it will fall back to using
the default cache. You may select an alternate cache backend to use with
the <code class="docutils literal"><span class="pre">using</span></code> keyword argument, which must be the last argument to the tag.</p>
</div>
<div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">cache</span> <span class="m">300</span> <span class="nv">local-thing</span> <span class="p">...</span>  <span class="nv">using</span><span class="o">=</span><span class="s2">&quot;localcache&quot;</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>It is considered an error to specify a cache name that is not configured.</p>
<dl class="function">
<dt id="django.core.cache.utils.make_template_fragment_key">
<code class="descclassname">django.core.cache.utils.</code><code class="descname">make_template_fragment_key</code>(<em>fragment_name</em>, <em>vary_on=None</em>)<a class="headerlink" href="#django.core.cache.utils.make_template_fragment_key" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If you want to obtain the cache key used for a cached fragment, you can use
<code class="docutils literal"><span class="pre">make_template_fragment_key</span></code>. <code class="docutils literal"><span class="pre">fragment_name</span></code> is the same as second argument
to the <code class="docutils literal"><span class="pre">cache</span></code> template tag; <code class="docutils literal"><span class="pre">vary_on</span></code> is a list of all additional arguments
passed to the tag. This function can be useful for invalidating or overwriting
a cached item, for example:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">cache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache.utils</span> <span class="kn">import</span> <span class="n">make_template_fragment_key</span>
<span class="go"># cache key for {% cache 500 sidebar username %}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">key</span> <span class="o">=</span> <span class="n">make_template_fragment_key</span><span class="p">(</span><span class="s1">&#39;sidebar&#39;</span><span class="p">,</span> <span class="p">[</span><span class="n">username</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="c1"># invalidates cached template fragment</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-low-level-cache-api">
<span id="the-low-level-cache-api"></span><h2>The low-level cache API<a class="headerlink" href="#the-low-level-cache-api" title="Permalink to this headline">¶</a></h2>
<p>Sometimes, caching an entire rendered page doesn&#8217;t gain you very much and is,
in fact, inconvenient overkill.</p>
<p>Perhaps, for instance, your site includes a view whose results depend on
several expensive queries, the results of which change at different intervals.
In this case, it would not be ideal to use the full-page caching that the
per-site or per-view cache strategies offer, because you wouldn&#8217;t want to
cache the entire result (since some of the data changes often), but you&#8217;d still
want to cache the results that rarely change.</p>
<p>For cases like this, Django exposes a simple, low-level cache API. You can use
this API to store objects in the cache with any level of granularity you like.
You can cache any Python object that can be pickled safely: strings,
dictionaries, lists of model objects, and so forth. (Most common Python objects
can be pickled; refer to the Python documentation for more information about
pickling.)</p>
<div class="section" id="s-accessing-the-cache">
<span id="accessing-the-cache"></span><h3>Accessing the cache<a class="headerlink" href="#accessing-the-cache" title="Permalink to this headline">¶</a></h3>
<dl class="data">
<dt id="django.core.cache.caches">
<code class="descclassname">django.core.cache.</code><code class="descname">caches</code><a class="headerlink" href="#django.core.cache.caches" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>You can access the caches configured in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting
through a dict-like object: <code class="docutils literal"><span class="pre">django.core.cache.caches</span></code>. Repeated
requests for the same alias in the same thread will return the same
object.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">caches</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache1</span> <span class="o">=</span> <span class="n">caches</span><span class="p">[</span><span class="s1">&#39;myalias&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache2</span> <span class="o">=</span> <span class="n">caches</span><span class="p">[</span><span class="s1">&#39;myalias&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache1</span> <span class="ow">is</span> <span class="n">cache2</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If the named key does not exist, <code class="docutils literal"><span class="pre">InvalidCacheBackendError</span></code> will be
raised.</p>
<p>To provide thread-safety, a different instance of the cache backend will
be returned for each thread.</p>
</dd></dl>

<dl class="data">
<dt id="django.core.cache.cache">
<code class="descclassname">django.core.cache.</code><code class="descname">cache</code><a class="headerlink" href="#django.core.cache.cache" title="Permalink to this definition">¶</a></dt>
<dd><p>As a shortcut, the default cache is available as
<code class="docutils literal"><span class="pre">django.core.cache.cache</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">cache</span>
</pre></div>
</div>
<p>This object is equivalent to <code class="docutils literal"><span class="pre">caches['default']</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="django.core.cache.get_cache">
<code class="descclassname">django.core.cache.</code><code class="descname">get_cache</code>(<em>backend</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.core.cache.get_cache" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 1.7: </span>This function has been deprecated in favor of
<a class="reference internal" href="#django.core.cache.caches" title="django.core.cache.caches"><code class="xref py py-data docutils literal"><span class="pre">caches</span></code></a>.</p>
</div>
<p>Before Django 1.7 this function was the canonical way to obtain a cache
instance. It could also be used to create a new cache instance with a
different configuration.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">get_cache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_cache</span><span class="p">(</span><span class="s1">&#39;default&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_cache</span><span class="p">(</span><span class="s1">&#39;django.core.cache.backends.memcached.MemcachedCache&#39;</span><span class="p">,</span> <span class="n">LOCATION</span><span class="o">=</span><span class="s1">&#39;127.0.0.2&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_cache</span><span class="p">(</span><span class="s1">&#39;default&#39;</span><span class="p">,</span> <span class="n">TIMEOUT</span><span class="o">=</span><span class="mi">300</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="s-basic-usage">
<span id="basic-usage"></span><h3>Basic usage<a class="headerlink" href="#basic-usage" title="Permalink to this headline">¶</a></h3>
<p>The basic interface is <code class="docutils literal"><span class="pre">set(key,</span> <span class="pre">value,</span> <span class="pre">timeout)</span></code> and <code class="docutils literal"><span class="pre">get(key)</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;hello, world!&#39;</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="go">&#39;hello, world!&#39;</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">timeout</span></code> argument is optional and defaults to the <code class="docutils literal"><span class="pre">timeout</span></code> argument
of the appropriate backend in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting (explained above).
It&#8217;s the number of seconds the value should be stored in the cache. Passing in
<code class="docutils literal"><span class="pre">None</span></code> for <code class="docutils literal"><span class="pre">timeout</span></code> will cache the value forever. A <code class="docutils literal"><span class="pre">timeout</span></code> of <code class="docutils literal"><span class="pre">0</span></code>
won&#8217;t cache the value.</p>
<p>If the object doesn&#8217;t exist in the cache, <code class="docutils literal"><span class="pre">cache.get()</span></code> returns <code class="docutils literal"><span class="pre">None</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># Wait 30 seconds for &#39;my_key&#39; to expire...</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="bp">None</span>
</pre></div>
</div>
<p>We advise against storing the literal value <code class="docutils literal"><span class="pre">None</span></code> in the cache, because you
won&#8217;t be able to distinguish between your stored <code class="docutils literal"><span class="pre">None</span></code> value and a cache
miss signified by a return value of <code class="docutils literal"><span class="pre">None</span></code>.</p>
<p><code class="docutils literal"><span class="pre">cache.get()</span></code> can take a <code class="docutils literal"><span class="pre">default</span></code> argument. This specifies which value to
return if the object doesn&#8217;t exist in the cache:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;has expired&#39;</span><span class="p">)</span>
<span class="go">&#39;has expired&#39;</span>
</pre></div>
</div>
<p>To add a key only if it doesn&#8217;t already exist, use the <code class="docutils literal"><span class="pre">add()</span></code> method.
It takes the same parameters as <code class="docutils literal"><span class="pre">set()</span></code>, but it will not attempt to
update the cache if the key specified is already present:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">,</span> <span class="s1">&#39;Initial value&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">,</span> <span class="s1">&#39;New value&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">)</span>
<span class="go">&#39;Initial value&#39;</span>
</pre></div>
</div>
<p>If you need to know whether <code class="docutils literal"><span class="pre">add()</span></code> stored a value in the cache, you can
check the return value. It will return <code class="docutils literal"><span class="pre">True</span></code> if the value was stored,
<code class="docutils literal"><span class="pre">False</span></code> otherwise.</p>
<p>There&#8217;s also a <code class="docutils literal"><span class="pre">get_many()</span></code> interface that only hits the cache once.
<code class="docutils literal"><span class="pre">get_many()</span></code> returns a dictionary with all the keys you asked for that
actually exist in the cache (and haven&#8217;t expired):</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
<span class="go">{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}</span>
</pre></div>
</div>
<p>To set multiple values more efficiently, use <code class="docutils literal"><span class="pre">set_many()</span></code> to pass a dictionary
of key-value pairs:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set_many</span><span class="p">({</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
<span class="go">{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}</span>
</pre></div>
</div>
<p>Like <code class="docutils literal"><span class="pre">cache.set()</span></code>, <code class="docutils literal"><span class="pre">set_many()</span></code> takes an optional <code class="docutils literal"><span class="pre">timeout</span></code> parameter.</p>
<p>You can delete keys explicitly with <code class="docutils literal"><span class="pre">delete()</span></code>. This is an easy way of
clearing the cache for a particular object:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to clear a bunch of keys at once, <code class="docutils literal"><span class="pre">delete_many()</span></code> can take a list
of keys to be cleared:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>Finally, if you want to delete all the keys in the cache, use
<code class="docutils literal"><span class="pre">cache.clear()</span></code>.  Be careful with this; <code class="docutils literal"><span class="pre">clear()</span></code> will remove <em>everything</em>
from the cache, not just the keys set by your application.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
</pre></div>
</div>
<p>You can also increment or decrement a key that already exists using the
<code class="docutils literal"><span class="pre">incr()</span></code> or <code class="docutils literal"><span class="pre">decr()</span></code> methods, respectively. By default, the existing cache
value will incremented or decremented by 1. Other increment/decrement values
can be specified by providing an argument to the increment/decrement call. A
ValueError will be raised if you attempt to increment or decrement a
nonexistent cache key.:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">)</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="go">6</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal"><span class="pre">incr()</span></code>/<code class="docutils literal"><span class="pre">decr()</span></code> methods are not guaranteed to be atomic. On those
backends that support atomic increment/decrement (most notably, the
memcached backend), increment and decrement operations will be atomic.
However, if the backend doesn&#8217;t natively provide an increment/decrement
operation, it will be implemented using a two-step retrieve/update.</p>
</div>
<p>You can close the connection to your cache with <code class="docutils literal"><span class="pre">close()</span></code> if implemented by
the cache backend.</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For caches that don&#8217;t implement <code class="docutils literal"><span class="pre">close</span></code> methods it is a no-op.</p>
</div>
</div>
<div class="section" id="s-cache-key-prefixing">
<span id="s-id7"></span><span id="cache-key-prefixing"></span><span id="id7"></span><h3>Cache key prefixing<a class="headerlink" href="#cache-key-prefixing" title="Permalink to this headline">¶</a></h3>
<p>If you are sharing a cache instance between servers, or between your
production and development environments, it&#8217;s possible for data cached
by one server to be used by another server. If the format of cached
data is different between servers, this can lead to some very hard to
diagnose problems.</p>
<p>To prevent this, Django provides the ability to prefix all cache keys
used by a server. When a particular cache key is saved or retrieved,
Django will automatically prefix the cache key with the value of the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">KEY_PREFIX</span></code></a> cache setting.</p>
<p>By ensuring each Django instance has a different
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal"><span class="pre">KEY_PREFIX</span></code></a>, you can ensure that there will be no
collisions in cache values.</p>
</div>
<div class="section" id="s-cache-versioning">
<span id="s-id8"></span><span id="cache-versioning"></span><span id="id8"></span><h3>Cache versioning<a class="headerlink" href="#cache-versioning" title="Permalink to this headline">¶</a></h3>
<p>When you change running code that uses cached values, you may need to
purge any existing cached values. The easiest way to do this is to
flush the entire cache, but this can lead to the loss of cache values
that are still valid and useful.</p>
<p>Django provides a better way to target individual cache values.
Django&#8217;s cache framework has a system-wide version identifier,
specified using the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-VERSION"><code class="xref std std-setting docutils literal"><span class="pre">VERSION</span></code></a> cache setting.
The value of this setting is automatically combined with the cache
prefix and the user-provided cache key to obtain the final cache key.</p>
<p>By default, any key request will automatically include the site
default cache key version. However, the primitive cache functions all
include a <code class="docutils literal"><span class="pre">version</span></code> argument, so you can specify a particular cache
key version to set or get. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># Set version 2 of a cache key</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;hello world!&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="c1"># Get the default version (assuming version=1)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="bp">None</span>
<span class="c1"># Get version 2 of the same key</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="s1">&#39;hello world!&#39;</span>
</pre></div>
</div>
<p>The version of a specific key can be incremented and decremented using
the <code class="docutils literal"><span class="pre">incr_version()</span></code> and <code class="docutils literal"><span class="pre">decr_version()</span></code> methods. This
enables specific keys to be bumped to a new version, leaving other
keys unaffected. Continuing our previous example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># Increment the version of &#39;my_key&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">incr_version</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="c1"># The default version still isn&#39;t available</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="bp">None</span>
<span class="c1"># Version 2 isn&#39;t available, either</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="bp">None</span>
<span class="c1"># But version 3 *is* available</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="s1">&#39;hello world!&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-cache-key-transformation">
<span id="s-id9"></span><span id="cache-key-transformation"></span><span id="id9"></span><h3>Cache key transformation<a class="headerlink" href="#cache-key-transformation" title="Permalink to this headline">¶</a></h3>
<p>As described in the previous two sections, the cache key provided by a
user is not used verbatim &#8211; it is combined with the cache prefix and
key version to provide a final cache key. By default, the three parts
are joined using colons to produce a final string:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">make_key</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">key_prefix</span><span class="p">,</span> <span class="n">version</span><span class="p">):</span>
    <span class="k">return</span> <span class="s1">&#39;:&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">key_prefix</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">version</span><span class="p">),</span> <span class="n">key</span><span class="p">])</span>
</pre></div>
</div>
<p>If you want to combine the parts in different ways, or apply other
processing to the final key (e.g., taking a hash digest of the key
parts), you can provide a custom key function.</p>
<p>The <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_FUNCTION"><code class="xref std std-setting docutils literal"><span class="pre">KEY_FUNCTION</span></code></a> cache setting
specifies a dotted-path to a function matching the prototype of
<code class="docutils literal"><span class="pre">make_key()</span></code> above. If provided, this custom key function will
be used instead of the default key combining function.</p>
</div>
<div class="section" id="s-cache-key-warnings">
<span id="cache-key-warnings"></span><h3>Cache key warnings<a class="headerlink" href="#cache-key-warnings" title="Permalink to this headline">¶</a></h3>
<p>Memcached, the most commonly-used production cache backend, does not allow
cache keys longer than 250 characters or containing whitespace or control
characters, and using such keys will cause an exception. To encourage
cache-portable code and minimize unpleasant surprises, the other built-in cache
backends issue a warning (<code class="docutils literal"><span class="pre">django.core.cache.backends.base.CacheKeyWarning</span></code>)
if a key is used that would cause an error on memcached.</p>
<p>If you are using a production backend that can accept a wider range of keys (a
custom backend, or one of the non-memcached built-in backends), and want to use
this wider range without warnings, you can silence <code class="docutils literal"><span class="pre">CacheKeyWarning</span></code> with
this code in the <code class="docutils literal"><span class="pre">management</span></code> module of one of your
<a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></code></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>

<span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">CacheKeyWarning</span>

<span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;ignore&quot;</span><span class="p">,</span> <span class="n">CacheKeyWarning</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to instead provide custom key validation logic for one of the
built-in backends, you can subclass it, override just the <code class="docutils literal"><span class="pre">validate_key</span></code>
method, and follow the instructions for <a class="reference internal" href="#using-a-custom-cache-backend">using a custom cache backend</a>. For
instance, to do this for the <code class="docutils literal"><span class="pre">locmem</span></code> backend, put this code in a module:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.cache.backends.locmem</span> <span class="kn">import</span> <span class="n">LocMemCache</span>

<span class="k">class</span> <span class="nc">CustomLocMemCache</span><span class="p">(</span><span class="n">LocMemCache</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">validate_key</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Custom validation, raising exceptions or warnings as needed.&quot;&quot;&quot;</span>
        <span class="c1"># ...</span>
</pre></div>
</div>
<p>...and use the dotted Python path to this class in the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> portion of your <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal"><span class="pre">CACHES</span></code></a> setting.</p>
</div>
</div>
<div class="section" id="s-downstream-caches">
<span id="downstream-caches"></span><h2>Downstream caches<a class="headerlink" href="#downstream-caches" title="Permalink to this headline">¶</a></h2>
<p>So far, this document has focused on caching your <em>own</em> data. But another type
of caching is relevant to Web development, too: caching performed by
&#8220;downstream&#8221; caches. These are systems that cache pages for users even before
the request reaches your Web site.</p>
<p>Here are a few examples of downstream caches:</p>
<ul class="simple">
<li>Your ISP may cache certain pages, so if you requested a page from
<a class="reference external" href="http://example.com/">http://example.com/</a>, your ISP would send you the page without having to
access example.com directly. The maintainers of example.com have no
knowledge of this caching; the ISP sits between example.com and your Web
browser, handling all of the caching transparently.</li>
<li>Your Django Web site may sit behind a <em>proxy cache</em>, such as Squid Web
Proxy Cache (<a class="reference external" href="http://www.squid-cache.org/">http://www.squid-cache.org/</a>), that caches pages for
performance. In this case, each request first would be handled by the
proxy, and it would be passed to your application only if needed.</li>
<li>Your Web browser caches pages, too. If a Web page sends out the
appropriate headers, your browser will use the local cached copy for
subsequent requests to that page, without even contacting the Web page
again to see whether it has changed.</li>
</ul>
<p>Downstream caching is a nice efficiency boost, but there&#8217;s a danger to it:
Many Web pages&#8217; contents differ based on authentication and a host of other
variables, and cache systems that blindly save pages based purely on URLs could
expose incorrect or sensitive data to subsequent visitors to those pages.</p>
<p>For example, say you operate a Web email system, and the contents of the
&#8220;inbox&#8221; page obviously depend on which user is logged in. If an ISP blindly
cached your site, then the first user who logged in through that ISP would have
their user-specific inbox page cached for subsequent visitors to the site.
That&#8217;s not cool.</p>
<p>Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
exist to instruct downstream caches to differ their cache contents depending on
designated variables, and to tell caching mechanisms not to cache particular
pages. We&#8217;ll look at some of these headers in the sections that follow.</p>
</div>
<div class="section" id="s-using-vary-headers">
<span id="s-id10"></span><span id="using-vary-headers"></span><span id="id10"></span><h2>Using Vary headers<a class="headerlink" href="#using-vary-headers" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal"><span class="pre">Vary</span></code> header defines which request headers a cache
mechanism should take into account when building its cache key. For example, if
the contents of a Web page depend on a user&#8217;s language preference, the page is
said to &#8220;vary on language.&#8221;</p>
<p>By default, Django&#8217;s cache system creates its cache keys using the requested
fully-qualified URL &#8211; e.g.,
<code class="docutils literal"><span class="pre">&quot;http://www.example.com/stories/2005/?order_by=author&quot;</span></code>. This means every
request to that URL will use the same cached version, regardless of user-agent
differences such as cookies or language preferences. However, if this page
produces different content based on some difference in request headers &#8211; such
as a cookie, or a language, or a user-agent &#8211; you&#8217;ll need to use the <code class="docutils literal"><span class="pre">Vary</span></code>
header to tell caching mechanisms that the page output depends on those things.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>Cache keys use the request&#8217;s fully-qualified URL rather than just the path
and query string.</p>
</div>
<p>To do this in Django, use the convenient
<a class="reference internal" href="http/decorators.html#django.views.decorators.vary.vary_on_headers" title="django.views.decorators.vary.vary_on_headers"><code class="xref py py-func docutils literal"><span class="pre">django.views.decorators.vary.vary_on_headers()</span></code></a> view decorator, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.vary</span> <span class="kn">import</span> <span class="n">vary_on_headers</span>

<span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>In this case, a caching mechanism (such as Django&#8217;s own cache middleware) will
cache a separate version of the page for each unique user-agent.</p>
<p>The advantage to using the <code class="docutils literal"><span class="pre">vary_on_headers</span></code> decorator rather than manually
setting the <code class="docutils literal"><span class="pre">Vary</span></code> header (using something like
<code class="docutils literal"><span class="pre">response['Vary']</span> <span class="pre">=</span> <span class="pre">'user-agent'</span></code>) is that the decorator <em>adds</em> to the
<code class="docutils literal"><span class="pre">Vary</span></code> header (which may already exist), rather than setting it from scratch
and potentially overriding anything that was already in there.</p>
<p>You can pass multiple headers to <code class="docutils literal"><span class="pre">vary_on_headers()</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">,</span> <span class="s1">&#39;Cookie&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>This tells downstream caches to vary on <em>both</em>, which means each combination of
user-agent and cookie will get its own cache value. For example, a request with
the user-agent <code class="docutils literal"><span class="pre">Mozilla</span></code> and the cookie value <code class="docutils literal"><span class="pre">foo=bar</span></code> will be considered
different from a request with the user-agent <code class="docutils literal"><span class="pre">Mozilla</span></code> and the cookie value
<code class="docutils literal"><span class="pre">foo=ham</span></code>.</p>
<p>Because varying on cookie is so common, there&#8217;s a
<a class="reference internal" href="http/decorators.html#django.views.decorators.vary.vary_on_cookie" title="django.views.decorators.vary.vary_on_cookie"><code class="xref py py-func docutils literal"><span class="pre">django.views.decorators.vary.vary_on_cookie()</span></code></a> decorator. These two views
are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="nd">@vary_on_cookie</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>

<span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;Cookie&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>The headers you pass to <code class="docutils literal"><span class="pre">vary_on_headers</span></code> are not case sensitive;
<code class="docutils literal"><span class="pre">&quot;User-Agent&quot;</span></code> is the same thing as <code class="docutils literal"><span class="pre">&quot;user-agent&quot;</span></code>.</p>
<p>You can also use a helper function, <a class="reference internal" href="../ref/utils.html#django.utils.cache.patch_vary_headers" title="django.utils.cache.patch_vary_headers"><code class="xref py py-func docutils literal"><span class="pre">django.utils.cache.patch_vary_headers()</span></code></a>,
directly. This function sets, or adds to, the <code class="docutils literal"><span class="pre">Vary</span> <span class="pre">header</span></code>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils.cache</span> <span class="kn">import</span> <span class="n">patch_vary_headers</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s1">&#39;template_name&#39;</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
    <span class="n">patch_vary_headers</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cookie&#39;</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">patch_vary_headers</span></code> takes an <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> instance as
its first argument and a list/tuple of case-insensitive header names as its
second argument.</p>
<p>For more on Vary headers, see the <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44">official Vary spec</a>.</p>
</div>
<div class="section" id="s-controlling-cache-using-other-headers">
<span id="controlling-cache-using-other-headers"></span><h2>Controlling cache: Using other headers<a class="headerlink" href="#controlling-cache-using-other-headers" title="Permalink to this headline">¶</a></h2>
<p>Other problems with caching are the privacy of data and the question of where
data should be stored in a cascade of caches.</p>
<p>A user usually faces two kinds of caches: their own browser cache (a private
cache) and their provider&#8217;s cache (a public cache). A public cache is used by
multiple users and controlled by someone else. This poses problems with
sensitive data&#8211;you don&#8217;t want, say, your bank account number stored in a
public cache. So Web applications need a way to tell caches which data is
private and which is public.</p>
<p>The solution is to indicate a page&#8217;s cache should be &#8220;private.&#8221; To do this in
Django, use the <code class="docutils literal"><span class="pre">cache_control</span></code> view decorator. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_control</span>

<span class="nd">@cache_control</span><span class="p">(</span><span class="n">private</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>This decorator takes care of sending out the appropriate HTTP header behind the
scenes.</p>
<p>Note that the cache control settings &#8220;private&#8221; and &#8220;public&#8221; are mutually
exclusive. The decorator ensures that the &#8220;public&#8221; directive is removed if
&#8220;private&#8221; should be set (and vice versa). An example use of the two directives
would be a blog site that offers both private and public entries. Public
entries may be cached on any shared cache. The following code uses
<a class="reference internal" href="../ref/utils.html#django.utils.cache.patch_cache_control" title="django.utils.cache.patch_cache_control"><code class="xref py py-func docutils literal"><span class="pre">django.utils.cache.patch_cache_control()</span></code></a>, the manual way to modify the
cache control header (it is internally called by the <code class="docutils literal"><span class="pre">cache_control</span></code>
decorator):</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">patch_cache_control</span>
<span class="kn">from</span> <span class="nn">django.views.decorators.vary</span> <span class="kn">import</span> <span class="n">vary_on_cookie</span>

<span class="nd">@vary_on_cookie</span>
<span class="k">def</span> <span class="nf">list_blog_entries_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_anonymous</span><span class="p">():</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">render_only_public_entries</span><span class="p">()</span>
        <span class="n">patch_cache_control</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">public</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">render_private_and_public_entries</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="p">)</span>
        <span class="n">patch_cache_control</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">private</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p>There are a few other ways to control cache parameters. For example, HTTP
allows applications to do the following:</p>
<ul class="simple">
<li>Define the maximum time a page should be cached.</li>
<li>Specify whether a cache should always check for newer versions, only
delivering the cached content when there are no changes. (Some caches
might deliver cached content even if the server page changed, simply
because the cache copy isn&#8217;t yet expired.)</li>
</ul>
<p>In Django, use the <code class="docutils literal"><span class="pre">cache_control</span></code> view decorator to specify these cache
parameters. In this example, <code class="docutils literal"><span class="pre">cache_control</span></code> tells caches to revalidate the
cache on every access and to store cached versions for, at most, 3,600 seconds:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_control</span>

<span class="nd">@cache_control</span><span class="p">(</span><span class="n">must_revalidate</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">max_age</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>Any valid <code class="docutils literal"><span class="pre">Cache-Control</span></code> HTTP directive is valid in <code class="docutils literal"><span class="pre">cache_control()</span></code>.
Here&#8217;s a full list:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">public=True</span></code></li>
<li><code class="docutils literal"><span class="pre">private=True</span></code></li>
<li><code class="docutils literal"><span class="pre">no_cache=True</span></code></li>
<li><code class="docutils literal"><span class="pre">no_transform=True</span></code></li>
<li><code class="docutils literal"><span class="pre">must_revalidate=True</span></code></li>
<li><code class="docutils literal"><span class="pre">proxy_revalidate=True</span></code></li>
<li><code class="docutils literal"><span class="pre">max_age=num_seconds</span></code></li>
<li><code class="docutils literal"><span class="pre">s_maxage=num_seconds</span></code></li>
</ul>
<p>For explanation of Cache-Control HTTP directives, see the <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9">Cache-Control spec</a>.</p>
<p>(Note that the caching middleware already sets the cache header&#8217;s max-age with
the value of the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> setting. If you use a custom
<code class="docutils literal"><span class="pre">max_age</span></code> in a <code class="docutils literal"><span class="pre">cache_control</span></code> decorator, the decorator will take
precedence, and the header values will be merged correctly.)</p>
<p>If you want to use headers to disable caching altogether,
<code class="docutils literal"><span class="pre">django.views.decorators.cache.never_cache</span></code> is a view decorator that adds
headers to ensure the response won&#8217;t be cached by browsers or other caches.
Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">never_cache</span>

<span class="nd">@never_cache</span>
<span class="k">def</span> <span class="nf">myview</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
</div>
<div class="section" id="s-order-of-middleware-classes">
<span id="order-of-middleware-classes"></span><h2>Order of MIDDLEWARE_CLASSES<a class="headerlink" href="#order-of-middleware-classes" title="Permalink to this headline">¶</a></h2>
<p>If you use caching middleware, it&#8217;s important to put each half in the right
place within the <a class="reference internal" href="../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> setting. That&#8217;s because the cache
middleware needs to know which headers by which to vary the cache storage.
Middleware always adds something to the <code class="docutils literal"><span class="pre">Vary</span></code> response header when it can.</p>
<p><code class="docutils literal"><span class="pre">UpdateCacheMiddleware</span></code> runs during the response phase, where middleware is
run in reverse order, so an item at the top of the list runs <em>last</em> during the
response phase. Thus, you need to make sure that <code class="docutils literal"><span class="pre">UpdateCacheMiddleware</span></code>
appears <em>before</em> any other middleware that might add something to the <code class="docutils literal"><span class="pre">Vary</span></code>
header. The following middleware modules do so:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">SessionMiddleware</span></code> adds <code class="docutils literal"><span class="pre">Cookie</span></code></li>
<li><code class="docutils literal"><span class="pre">GZipMiddleware</span></code> adds <code class="docutils literal"><span class="pre">Accept-Encoding</span></code></li>
<li><code class="docutils literal"><span class="pre">LocaleMiddleware</span></code> adds <code class="docutils literal"><span class="pre">Accept-Language</span></code></li>
</ul>
<p><code class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></code>, on the other hand, runs during the request phase,
where middleware is applied first-to-last, so an item at the top of the list
runs <em>first</em> during the request phase. The <code class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></code> also
needs to run after other middleware updates the <code class="docutils literal"><span class="pre">Vary</span></code> header, so
<code class="docutils literal"><span class="pre">FetchFromCacheMiddleware</span></code> must be <em>after</em> any item that does so.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Django&#8217;s cache framework</a><ul>
<li><a class="reference internal" href="#setting-up-the-cache">Setting up the cache</a><ul>
<li><a class="reference internal" href="#memcached">Memcached</a></li>
<li><a class="reference internal" href="#database-caching">Database caching</a><ul>
<li><a class="reference internal" href="#creating-the-cache-table">Creating the cache table</a></li>
<li><a class="reference internal" href="#multiple-databases">Multiple databases</a></li>
</ul>
</li>
<li><a class="reference internal" href="#filesystem-caching">Filesystem caching</a></li>
<li><a class="reference internal" href="#local-memory-caching">Local-memory caching</a></li>
<li><a class="reference internal" href="#dummy-caching-for-development">Dummy caching (for development)</a></li>
<li><a class="reference internal" href="#using-a-custom-cache-backend">Using a custom cache backend</a></li>
<li><a class="reference internal" href="#cache-arguments">Cache arguments</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-per-site-cache">The per-site cache</a></li>
<li><a class="reference internal" href="#the-per-view-cache">The per-view cache</a><ul>
<li><a class="reference internal" href="#specifying-per-view-cache-in-the-urlconf">Specifying per-view cache in the URLconf</a></li>
</ul>
</li>
<li><a class="reference internal" href="#template-fragment-caching">Template fragment caching</a></li>
<li><a class="reference internal" href="#the-low-level-cache-api">The low-level cache API</a><ul>
<li><a class="reference internal" href="#accessing-the-cache">Accessing the cache</a></li>
<li><a class="reference internal" href="#basic-usage">Basic usage</a></li>
<li><a class="reference internal" href="#cache-key-prefixing">Cache key prefixing</a></li>
<li><a class="reference internal" href="#cache-versioning">Cache versioning</a></li>
<li><a class="reference internal" href="#cache-key-transformation">Cache key transformation</a></li>
<li><a class="reference internal" href="#cache-key-warnings">Cache key warnings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#downstream-caches">Downstream caches</a></li>
<li><a class="reference internal" href="#using-vary-headers">Using Vary headers</a></li>
<li><a class="reference internal" href="#controlling-cache-using-other-headers">Controlling cache: Using other headers</a></li>
<li><a class="reference internal" href="#order-of-middleware-classes">Order of MIDDLEWARE_CLASSES</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="auth/customizing.html">Customizing authentication in Django</a></li>
    
    
      <li>Next: <a href="conditional-view-processing.html">Conditional View Processing</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.8.19 documentation</a>
        
          <ul><li><a href="index.html">Using Django</a>
        
        <ul><li>Django&#8217;s cache framework</li></ul>
        </li></ul>
      </li>
  </ul>

  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/cache.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 10, 2018</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="auth/customizing.html" title="Customizing authentication in Django">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="conditional-view-processing.html" title="Conditional View Processing">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>