Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Changed docs/cache to add docs for site-wide caching, via the cache m…

…iddleware

git-svn-id: http://code.djangoproject.com/svn/django/trunk@224 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b0e1a1dda8c020cd6ebe07640fd5929cd5ee3345 1 parent 12321ea
Adrian Holovaty authored July 19, 2005

Showing 1 changed file with 96 additions and 57 deletions. Show diff stats Hide diff stats

  1. 153  docs/cache.txt
153  docs/cache.txt
@@ -4,81 +4,120 @@ Django's cache framework
4 4
 
5 5
 So, you got slashdotted.  Now what?
6 6
 
7  
-Django's cache framework gives you two methods of caching dynamic pages in
8  
-memory or in a database: you can automatically cache the entire page, or you can manually
9  
-cache only the pieces that are difficult to produce.
  7
+Django's cache framework gives you three methods of caching dynamic pages in
  8
+memory or in a database. You can cache the output of entire pages, you can
  9
+cache only the pieces that are difficult to produce, or you can cache your
  10
+entire site.
10 11
 
11 12
 Setting up the cache
12 13
 ====================
13 14
 
14 15
 The cache framework is split into a set of "backends" that provide different
15  
-methods of caching data.  There's a simple single-process memory cache 
16  
-(mostly useful as a fallback), a database-backed cache, and a memcached_
17  
-backend (by far the fastest option if you've got the RAM).
  16
+methods of caching data. There's a simple single-process memory cache (mostly
  17
+useful as a fallback), a database-backed cache, and a memcached_ backend (by
  18
+far the fastest option if you've got the RAM).
18 19
 
19 20
 Before using the cache, you'll need to tell Django which cache backend you'd
20  
-like to use; do this by setting the ``CACHE_BACKEND`` in your settings file.
  21
+like to use. Do this by setting the ``CACHE_BACKEND`` in your settings file.
21 22
 
22  
-The CACHE_BACKEND setting is a quasi-URI; examples are:
  23
+The CACHE_BACKEND setting is a quasi-URI. Examples::
23 24
 
24 25
     ==============================  ===========================================
25 26
     CACHE_BACKEND                   Explanation
26 27
     ==============================  ===========================================
27  
-    memcached://127.0.0.1:11211/    A memcached backend; the server is running 
  28
+    memcached://127.0.0.1:11211/    A memcached backend; the server is running
28 29
                                     on localhost port 11211.
29  
-                                    
30  
-    db://tablename/                 A database backend (the db backend uses 
  30
+
  31
+    db://tablename/                 A database backend (the db backend uses
31 32
                                     the same database/username as the rest of
32 33
                                     the CMS, so only a table name is needed.)
33  
-                                    
  34
+
34 35
     simple:///                      A simple single-process memory cache; you
35 36
                                     probably don't want to use this except for
36  
-                                    testing. Note that this cache backend is 
  37
+                                    testing. Note that this cache backend is
37 38
                                     NOT threadsafe!
38 39
     ==============================  ===========================================
39 40
 
40  
-All caches may take arguments; these are given in query-string style.  Valid
  41
+All caches may take arguments -- they're given in query-string style.  Valid
41 42
 arguments are:
42 43
 
43  
-    timeout         
44  
-        Default timeout, in seconds, to use for the cache.  Defaults
45  
-        to 5 minutes (300 seconds).
46  
-                
47  
-    max_entries     
  44
+    timeout
  45
+        Default timeout, in seconds, to use for the cache. Defaults to 5
  46
+        minutes (300 seconds).
  47
+
  48
+    max_entries
48 49
         For the simple and database backends, the maximum number of entries
49 50
         allowed in the cache before it is cleaned.  Defaults to 300.
50  
-                
51  
-    cull_percentage 
52  
-        The percentage of entries that are culled when max_entries is reached. 
  51
+
  52
+    cull_percentage
  53
+        The percentage of entries that are culled when max_entries is reached.
53 54
         The actual percentage is 1/cull_percentage, so set cull_percentage=3 to
54 55
         cull 1/3 of the entries when max_entries is reached.
55  
-        
  56
+
56 57
         A value of 0 for cull_percentage means that the entire cache will be
57  
-        dumped when max_entries is reached.  This makes culling *much* faster
  58
+        dumped when max_entries is reached. This makes culling *much* faster
58 59
         at the expense of more cache misses.
59  
-                
  60
+
60 61
 For example::
61 62
 
62 63
     DB_CACHE = "memcached://127.0.0.1:11211/?timeout=60"
63 64
     DB_CACHE = "db://tablename/?timeout=120&max_entries=500&cull_percentage=4"
64  
-    
65  
-Invalid arguments are silently ignored, as are invalid values of known 
  65
+
  66
+Invalid arguments are silently ignored, as are invalid values of known
66 67
 arguments.
67 68
 
68  
-The per-page cache
  69
+The per-site cache
69 70
 ==================
70 71
 
71 72
 Once the cache is set up, the simplest way to use the cache is to simply
72  
-cache entire view functions.  ``django.views.decorators.cache`` defines
73  
-a ``cache_page`` decorator that will automatically cache the view's response
74  
-for you.  Using it couldn't be easier::
  73
+cache your entire site. Just add ``django.middleware.cache.CacheMiddleware``
  74
+to your ``MIDDLEWARE_CLASSES`` setting, as in this example::
  75
+
  76
+    MIDDLEWARE_CLASSES = (
  77
+        "django.middleware.common.CommonMiddleware",
  78
+        "django.middleware.cache.CacheMiddleware",
  79
+    )
  80
+
  81
+Then, add the following three required settings::
  82
+
  83
+* ``CACHE_MIDDLEWARE_SECONDS`` -- The number of seconds each page should be
  84
+  cached.
  85
+* ``CACHE_MIDDLEWARE_KEY_PREFIX`` -- If the cache is shared across multiple
  86
+  sites using the same Django installation, set this to the name of the site,
  87
+  or some other string that is unique to this Django instance, to prevent key
  88
+  collisions. Use an empty string if you don't care.
  89
+* ``CACHE_MIDDLEWARE_GZIP`` -- Either ``True`` or ``False``. If this is
  90
+  enabled, Django will gzip all content for users whose browsers support gzip
  91
+  encoding. Using gzip adds a level of overhead to page requests, but the
  92
+  overhead generally is cancelled out by the fact that gzipped pages are stored
  93
+  in the cache. That means subsequent requests won't have the overhead of
  94
+  zipping, and the cache will hold more pages because each one is smaller.
  95
+
  96
+Pages with GET or POST parameters won't be cached.
  97
+
  98
+The cache middleware also makes a few more optimizations:
  99
+
  100
+* Sets and deals with ``ETag`` headers.
  101
+* Sets the ``Content-Length`` header.
  102
+* Sets the ``Last-Modified`` header to the current date/time when a fresh
  103
+  (uncached) version of the page is requested.
  104
+
  105
+It doesn't matter where in the middleware stack you put the cache middleware.
  106
+
  107
+The per-page cache
  108
+==================
  109
+
  110
+A more granular way to use the caching framework is by caching the output of
  111
+individual views. ``django.views.decorators.cache`` defines a ``cache_page``
  112
+decorator that will automatically cache the view's response for you. It's easy
  113
+to use::
75 114
 
76 115
     from django.views.decorators.cache import cache_page
77  
-    
  116
+
78 117
     def slashdot_this(request):
79 118
         ...
80  
-   
81  
-    slashdot_this = cache_page(slashdot_this, 60 * 15):
  119
+
  120
+    slashdot_this = cache_page(slashdot_this, 60 * 15)
82 121
 
83 122
 Or, using Python 2.4's decorator syntax::
84 123
 
@@ -86,54 +125,54 @@ Or, using Python 2.4's decorator syntax::
86 125
     def slashdot_this(request):
87 126
         ...
88 127
 
89  
-This will cache the result of that view for 15 minutes (the cache timeout is
90  
-in seconds).
  128
+This will cache the result of that view for 15 minutes. (The cache timeout is
  129
+in seconds.)
91 130
 
92 131
 The low-level cache API
93 132
 =======================
94 133
 
95 134
 There are times, however, that caching an entire rendered page doesn't gain
96  
-you very much.  We often find that we only need to cache a list of object IDs
97  
-from an intensive database query, for example.  In cases like these, you
98  
-can use the cache API to store objects in the cache with any level of 
99  
-granularity you like.
  135
+you very much. The Django developers have found it's only necessary to cache a
  136
+list of object IDs from an intensive database query, for example. In cases like
  137
+these, you can use the cache API to store objects in the cache with any level
  138
+of granularity you like.
100 139
 
101  
-The cache API is almost shockingly simple::
  140
+The cache API is simple::
102 141
 
103 142
     # the cache module exports a cache object that's automatically
104 143
     # created from the CACHE_BACKEND setting
105 144
     >>> from django.core.cache import cache
106  
-    
  145
+
107 146
     # The basic interface is set(key, value, timeout_seconds) and get(key)
108 147
     >>> cache.set('my_key', 'hello, world!', 30)
109 148
     >>> cache.get('my_key')
110 149
     'hello, world!'
111  
-    
112  
-    # (wait 30 seconds...)
  150
+
  151
+    # (Wait 30 seconds...)
113 152
     >>> cache.get('my_key')
114 153
     None
115  
-    
116  
-    # get can take a default argument
  154
+
  155
+    # get() can take a default argument
117 156
     >>> cache.get('my_key', 'has_expired')
118 157
     'has_expired'
119  
-    
120  
-    # there's also a get_many interface that only hits the cache once
121  
-    # also, note that the timeout argument is optional and defaults
122  
-    # to what you've given in the settings file.
  158
+
  159
+    # There's also a get_many() interface that only hits the cache once.
  160
+    # Also, note that the timeout argument is optional and defaults to what
  161
+    # you've given in the settings file.
123 162
     >>> cache.set('a', 1)
124 163
     >>> cache.set('b', 2)
125 164
     >>> cache.set('c', 3)
  165
+
  166
+    # get_many() returns a dictionary with all the keys you asked for that
  167
+    # actually exist in the cache (and haven't expired).
126 168
     >>> cache.get_many(['a', 'b', 'c'])
127 169
     {'a': 1, 'b': 2, 'c': 3}
128  
-    # get_many returns a dict with all the keys you asked for that
129  
-    # actually exist in the cache (and haven't expired)
130  
-    
131  
-    # there's also a way to explicitly delete keys
  170
+
  171
+    # There's also a way to delete keys explicitly.
132 172
     >>> cache.delete('a')
133  
-    
134  
-Really, that's the entire API!  There's very few restrictions on what you can
  173
+
  174
+Really, that's the entire API! There are very few restrictions on what you can
135 175
 use the cache for; you can store any object in the cache that can be pickled
136 176
 safely, although keys must be strings.
137 177
 
138 178
 .. _memcached: http://www.danga.com/memcached/
139  
-

0 notes on commit b0e1a1d

Please sign in to comment.
Something went wrong with that request. Please try again.