Django

Code

Changeset 224

Show
Ignore:
Timestamp:
07/19/05 15:49:07 (3 years ago)
Author:
adrian
Message:

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

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/cache.txt

    r56 r224  
    55So, you got slashdotted.  Now what? 
    66 
    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. 
     7Django's cache framework gives you three methods of caching dynamic pages in 
     8memory or in a database. You can cache the output of entire pages, you can 
     9cache only the pieces that are difficult to produce, or you can cache your 
     10entire site. 
    1011 
    1112Setting up the cache 
     
    1314 
    1415The 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). 
     16methods of caching data. There's a simple single-process memory cache (mostly 
     17useful as a fallback), a database-backed cache, and a memcached_ backend (by 
     18far the fastest option if you've got the RAM). 
    1819 
    1920Before 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. 
     21like to use. Do this by setting the ``CACHE_BACKEND`` in your settings file. 
    2122 
    22 The CACHE_BACKEND setting is a quasi-URI; examples are
     23The CACHE_BACKEND setting is a quasi-URI. Examples:
    2324 
    2425    ==============================  =========================================== 
    2526    CACHE_BACKEND                   Explanation 
    2627    ==============================  =========================================== 
    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 
    2829                                    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 
    3132                                    the same database/username as the rest of 
    3233                                    the CMS, so only a table name is needed.) 
    33                                      
     34 
    3435    simple:///                      A simple single-process memory cache; you 
    3536                                    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 
    3738                                    NOT threadsafe! 
    3839    ==============================  =========================================== 
    3940 
    40 All caches may take arguments; these are given in query-string style.  Valid 
     41All caches may take arguments -- they're given in query-string style.  Valid 
    4142arguments are: 
    4243 
    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 
    4849        For the simple and database backends, the maximum number of entries 
    4950        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. 
    5354        The actual percentage is 1/cull_percentage, so set cull_percentage=3 to 
    5455        cull 1/3 of the entries when max_entries is reached. 
    55          
     56 
    5657        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 
    5859        at the expense of more cache misses. 
    59                  
     60 
    6061For example:: 
    6162 
    6263    DB_CACHE = "memcached://127.0.0.1:11211/?timeout=60" 
    6364    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 
     66Invalid arguments are silently ignored, as are invalid values of known 
    6667arguments. 
     68 
     69The per-site cache 
     70================== 
     71 
     72Once the cache is set up, the simplest way to use the cache is to simply 
     73cache your entire site. Just add ``django.middleware.cache.CacheMiddleware`` 
     74to your ``MIDDLEWARE_CLASSES`` setting, as in this example:: 
     75 
     76    MIDDLEWARE_CLASSES = ( 
     77        "django.middleware.common.CommonMiddleware", 
     78        "django.middleware.cache.CacheMiddleware", 
     79    ) 
     80 
     81Then, 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 
     96Pages with GET or POST parameters won't be cached. 
     97 
     98The 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 
     105It doesn't matter where in the middleware stack you put the cache middleware. 
    67106 
    68107The per-page cache 
    69108================== 
    70109 
    71 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:: 
     110A more granular way to use the caching framework is by caching the output of 
     111individual views. ``django.views.decorators.cache`` defines a ``cache_page`` 
     112decorator that will automatically cache the view's response for you. It's easy 
     113to use:: 
    75114 
    76115    from django.views.decorators.cache import cache_page 
    77      
     116 
    78117    def slashdot_this(request): 
    79118        ... 
    80     
    81     slashdot_this = cache_page(slashdot_this, 60 * 15): 
     119 
     120    slashdot_this = cache_page(slashdot_this, 60 * 15) 
    82121 
    83122Or, using Python 2.4's decorator syntax:: 
     
    87126        ... 
    88127 
    89 This will cache the result of that view for 15 minutes (the cache timeout is 
    90 in seconds). 
     128This will cache the result of that view for 15 minutes. (The cache timeout is 
     129in seconds.) 
    91130 
    92131The low-level cache API 
     
    94133 
    95134There 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. 
     135you very much. The Django developers have found it's only necessary to cache a 
     136list of object IDs from an intensive database query, for example. In cases like 
     137these, you can use the cache API to store objects in the cache with any level 
     138of granularity you like. 
    100139 
    101 The cache API is almost shockingly simple:: 
     140The cache API is simple:: 
    102141 
    103142    # the cache module exports a cache object that's automatically 
    104143    # created from the CACHE_BACKEND setting 
    105144    >>> from django.core.cache import cache 
    106      
     145 
    107146    # The basic interface is set(key, value, timeout_seconds) and get(key) 
    108147    >>> cache.set('my_key', 'hello, world!', 30) 
    109148    >>> cache.get('my_key') 
    110149    'hello, world!' 
    111      
    112     # (wait 30 seconds...) 
     150 
     151    # (Wait 30 seconds...) 
    113152    >>> cache.get('my_key') 
    114153    None 
    115      
    116     # get can take a default argument 
     154 
     155    # get() can take a default argument 
    117156    >>> cache.get('my_key', 'has_expired') 
    118157    '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. 
    123162    >>> cache.set('a', 1) 
    124163    >>> cache.set('b', 2) 
    125164    >>> 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). 
    126168    >>> cache.get_many(['a', 'b', 'c']) 
    127169    {'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. 
    132172    >>> cache.delete('a') 
    133      
    134 Really, that's the entire API! There's very few restrictions on what you can 
     173 
     174Really, that's the entire API! There are very few restrictions on what you can 
    135175use the cache for; you can store any object in the cache that can be pickled 
    136176safely, although keys must be strings. 
    137177 
    138178.. _memcached: http://www.danga.com/memcached/ 
    139