Django's cache framework

A fundamental trade-off in dynamic websites is, well, they're dynamic. Eachtime a user requests a page, the Web server makes all sorts of calculations —from database queries to template rendering to business logic — to create thepage that your site's visitor sees. This is a lot more expensive, from aprocessing-overhead perspective, than your standardread-a-file-off-the-filesystem server arrangement.

For most Web applications, this overhead isn't a big deal. Most Webapplications aren't washingtonpost.com or slashdot.org; they're simplysmall- to medium-sized sites with so-so traffic. But for medium- tohigh-traffic sites, it's essential to cut as much overhead as possible.

That's where caching comes in.

To cache something is to save the result of an expensive calculation so thatyou don't have to perform the calculation next time. Here's some pseudocodeexplaining how this would work for a dynamically generated Web page:

  1. given a URL, try finding that page in the cache
  2. if the page is in the cache:
  3. return the cached page
  4. else:
  5. generate the page
  6. save the generated page in the cache (for next time)
  7. return the generated page

Django comes with a robust cache system that lets you save dynamic pages sothey don't have to be calculated for each request. For convenience, Djangooffers different levels of cache granularity: You can cache the output ofspecific views, you can cache only the pieces that are difficult to produce,or you can cache your entire site.

Django also works well with "downstream" caches, such as Squid and browser-based caches. These are the types ofcaches that you don't directly control but to which you can provide hints (viaHTTP headers) about which parts of your site should be cached, and how.

See also

The Cache Framework design philosophyexplains a few of the design decisions of the framework.

Setting up the cache

The cache system requires a small amount of setup. Namely, you have to tell itwhere your cached data should live — whether in a database, on the filesystemor directly in memory. This is an important decision that affects your cache'sperformance; yes, some cache types are faster than others.

Your cache preference goes in the CACHES setting in yoursettings file. Here's an explanation of all available values forCACHES.

Memcached

The fastest, most efficient type of cache supported natively by Django,Memcached is an entirely memory-based cache server, originally developedto handle high loads at LiveJournal.com and subsequently open-sourced byDanga Interactive. It is used by sites such as Facebook and Wikipedia toreduce database access and dramatically increase site performance.

Memcached runs as a daemon and is allotted a specified amount of RAM. All itdoes is provide a fast interface for adding, retrieving and deleting data inthe cache. All data is stored directly in memory, so there's no overhead ofdatabase or filesystem usage.

After installing Memcached itself, you'll need to install a Memcachedbinding. There are several Python Memcached bindings available; thetwo most common are python-memcached and pylibmc.

To use Memcached with Django:

  • Set BACKEND todjango.core.cache.backends.memcached.MemcachedCache ordjango.core.cache.backends.memcached.PyLibMCCache (dependingon your chosen memcached binding)
  • Set LOCATION to ip:port values,where ip is the IP address of the Memcached daemon and port is theport on which Memcached is running, or to a unix:path value, wherepath is the path to a Memcached Unix socket file.In this example, Memcached is running on localhost (127.0.0.1) port 11211, usingthe python-memcached binding:
  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  4. 'LOCATION': '127.0.0.1:11211',
  5. }
  6. }

In this example, Memcached is available through a local Unix socket file/tmp/memcached.sock using the python-memcached binding:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  4. 'LOCATION': 'unix:/tmp/memcached.sock',
  5. }
  6. }

When using the pylibmc binding, do not include the unix:/ prefix:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
  4. 'LOCATION': '/tmp/memcached.sock',
  5. }
  6. }

One excellent feature of Memcached is its ability to share a cache overmultiple servers. This means you can run Memcached daemons on multiplemachines, and the program will treat the group of machines as a _single_cache, without the need to duplicate cache values on each machine. To takeadvantage of this feature, include all server addresses inLOCATION, either as a semicolon or commadelimited string, or as a list.

In this example, the cache is shared over Memcached instances running on IPaddress 172.19.26.240 and 172.19.26.242, both on port 11211:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  4. 'LOCATION': [
  5. '172.19.26.240:11211',
  6. '172.19.26.242:11211',
  7. ]
  8. }
  9. }

In the following example, the cache is shared over Memcached instances runningon the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and172.19.26.244 (port 11213):

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  4. 'LOCATION': [
  5. '172.19.26.240:11211',
  6. '172.19.26.242:11212',
  7. '172.19.26.244:11213',
  8. ]
  9. }
  10. }

A final point about Memcached is that memory-based caching has adisadvantage: because the cached data is stored in memory, the data will belost if your server crashes. Clearly, memory isn't intended for permanent datastorage, so don't rely on memory-based caching as your only data storage.Without a doubt, none of the Django caching backends should be used forpermanent storage — they're all intended to be solutions for caching, notstorage — but we point this out here because memory-based caching isparticularly temporary.

Changed in Django 1.11:The LOCATION setting now supports definingmultiple servers as a comma-delimited string.

Database caching

Django can store its cached data in your database. This works best if you'vegot a fast, well-indexed database server.

To use a database table as your cache backend:

  • Set BACKEND todjango.core.cache.backends.db.DatabaseCache
  • Set LOCATION to tablename, the name of thedatabase table. This name can be whatever you want, as long as it's a validtable name that's not already being used in your database.In this example, the cache table's name is my_cache_table:
  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
  4. 'LOCATION': 'my_cache_table',
  5. }
  6. }

Creating the cache table

Before using the database cache, you must create the cache table with thiscommand:

  1. python manage.py createcachetable

This creates a table in your database that is in the proper format thatDjango's database-cache system expects. The name of the table is taken fromLOCATION.

If you are using multiple database caches, createcachetable createsone table for each cache.

If you are using multiple databases, createcachetable observes theallow_migrate() method of your database routers (see below).

Like migrate, createcachetable won't touch an existingtable. It will only create missing tables.

To print the SQL that would be run, rather than run it, use thecreatecachetable —dry-run option.

Multiple databases

If you use database caching with multiple databases, you'll also needto set up routing instructions for your database cache table. For thepurposes of routing, the database cache table appears as a model namedCacheEntry, in an application named django_cache. This modelwon't appear in the models cache, but the model details can be usedfor routing purposes.

For example, the following router would direct all cache readoperations to cache_replica, and all write operations tocache_primary. The cache table will only be synchronized ontocache_primary:

  1. class CacheRouter:
  2. """A router to control all database cache operations"""
  3.  
  4. def db_for_read(self, model, **hints):
  5. "All cache read operations go to the replica"
  6. if model._meta.app_label == 'django_cache':
  7. return 'cache_replica'
  8. return None
  9.  
  10. def db_for_write(self, model, **hints):
  11. "All cache write operations go to primary"
  12. if model._meta.app_label == 'django_cache':
  13. return 'cache_primary'
  14. return None
  15.  
  16. def allow_migrate(self, db, app_label, model_name=None, **hints):
  17. "Only install the cache model on primary"
  18. if app_label == 'django_cache':
  19. return db == 'cache_primary'
  20. return None

If you don't specify routing directions for the database cache model,the cache backend will use the default database.

Of course, if you don't use the database cache backend, you don't needto worry about providing routing instructions for the database cachemodel.

Filesystem caching

The file-based backend serializes and stores each cache value as a separatefile. To use this backend set BACKEND to"django.core.cache.backends.filebased.FileBasedCache" andLOCATION to a suitable directory. For example,to store cached data in /var/tmp/django_cache, use this setting:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  4. 'LOCATION': '/var/tmp/django_cache',
  5. }
  6. }

If you're on Windows, put the drive letter at the beginning of the path,like this:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  4. 'LOCATION': 'c:/foo/bar',
  5. }
  6. }

The directory path should be absolute — that is, it should start at the rootof your filesystem. It doesn't matter whether you put a slash at the end of thesetting.

Make sure the directory pointed-to by this setting exists and is readable andwritable by the system user under which your Web server runs. Continuing theabove example, if your server runs as the user apache, make sure thedirectory /var/tmp/django_cache exists and is readable and writable by theuser apache.

Local-memory caching

This is the default cache if another is not specified in your settings file. Ifyou want the speed advantages of in-memory caching but don't have the capabilityof running Memcached, consider the local-memory cache backend. This cache isper-process (see below) and thread-safe. To use it, set BACKEND to "django.core.cache.backends.locmem.LocMemCache". Forexample:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  4. 'LOCATION': 'unique-snowflake',
  5. }
  6. }

The cache LOCATION is used to identify individualmemory stores. If you only have one locmem cache, you can omit theLOCATION; however, if you have more than one localmemory cache, you will need to assign a name to at least one of them inorder to keep them separate.

Note that each process will have its own private cache instance, which means nocross-process caching is possible. This obviously also means the local memorycache isn't particularly memory-efficient, so it's probably not a good choicefor production environments. It's nice for development.

Dummy caching (for development)

Finally, Django comes with a "dummy" cache that doesn't actually cache — itjust implements the cache interface without doing anything.

This is useful if you have a production site that uses heavy-duty caching invarious places but a development/test environment where you don't want to cacheand don't want to have to change your code to special-case the latter. Toactivate dummy caching, set BACKEND like so:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
  4. }
  5. }

使用自定义的缓存后台

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 externalcache backend with Django, use the Python import path as theBACKEND of the CACHES setting, like so:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'path.to.backend',
  4. }
  5. }

If you're building your own backend, you can use the standard cache backendsas reference implementations. You'll find the code in thedjango/core/cache/backends/ directory of the Django source.

Note: Without a really compelling reason, such as a host that doesn't supportthem, you should stick to the cache backends included with Django. They'vebeen well-tested and are easy to use.

Cache arguments

Each cache backend can be given additional arguments to control cachingbehavior. These arguments are provided as additional keys in theCACHES setting. Valid arguments are as follows:

  • TIMEOUT: The default timeout, inseconds, to use for the cache. This argument defaults to 300 seconds (5 minutes).You can set TIMEOUT to None so that, by default, cache keys neverexpire. A value of 0 causes keys to immediately expire (effectively"don't cache").

  • OPTIONS: Any options that should bepassed to the cache backend. The list of valid options will varywith each backend, and cache backends backed by a third-party librarywill pass their options directly to the underlying cache library.

Cache backends that implement their own culling strategy (i.e.,the locmem, filesystem and database backends) willhonor the following options:

  • MAX_ENTRIES: The maximum number of entries allowed inthe cache before old values are deleted. This argumentdefaults to 300.

  • CULL_FREQUENCY: The fraction of entries that are culledwhen MAX_ENTRIES is reached. The actual ratio is1 / CULL_FREQUENCY, so set CULL_FREQUENCY to 2 tocull half the entries when MAX_ENTRIES is reached. This argumentshould be an integer and defaults to 3.

A value of 0 for CULL_FREQUENCY means that theentire cache will be dumped when MAX_ENTRIES is reached.On some backends (database in particular) this makes culling _much_faster at the expense of more cache misses.

Memcached backends pass the contents of OPTIONSas keyword arguments to the client constructors, allowing for more advancedcontrol of client behavior. For example usage, see below.

  • KEY_PREFIX: A string that will beautomatically included (prepended by default) to all cache keysused by the Django server.

See the cache documentation formore information.

  • VERSION: The default version numberfor cache keys generated by the Django server.

See the cache documentation for moreinformation.

  • KEY_FUNCTIONA string containing a dotted path to a function that defines howto compose a prefix, version and key into a final cache key.

See the cache documentationfor more information.

In this example, a filesystem backend is being configured with a timeoutof 60 seconds, and a maximum capacity of 1000 items:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
  4. 'LOCATION': '/var/tmp/django_cache',
  5. 'TIMEOUT': 60,
  6. 'OPTIONS': {
  7. 'MAX_ENTRIES': 1000
  8. }
  9. }
  10. }

Here's an example configuration for a python-memcached based backend withan object size limit of 2MB:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
  4. 'LOCATION': '127.0.0.1:11211',
  5. 'OPTIONS': {
  6. 'server_max_value_length': 1024 * 1024 * 2,
  7. }
  8. }
  9. }

Here's an example configuration for a pylibmc based backend that enablesthe binary protocol, SASL authentication, and the ketama behavior mode:

  1. CACHES = {
  2. 'default': {
  3. 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
  4. 'LOCATION': '127.0.0.1:11211',
  5. 'OPTIONS': {
  6. 'binary': True,
  7. 'username': 'user',
  8. 'password': 'pass',
  9. 'behaviors': {
  10. 'ketama': True,
  11. }
  12. }
  13. }
  14. }

Changed in Django 1.11:Memcached backends can now be configured using OPTIONS.

In older versions, you could pass pylibmc behavior settings directlyinside OPTIONS. This is deprecated in favor of setting them under abehaviors key within OPTIONS instead.

The per-site cache

Once the cache is set up, the simplest way to use caching is to cache yourentire site. You'll need to add'django.middleware.cache.UpdateCacheMiddleware' and'django.middleware.cache.FetchFromCacheMiddleware' to yourMIDDLEWARE setting, as in this example:

  1. MIDDLEWARE = [
  2. 'django.middleware.cache.UpdateCacheMiddleware',
  3. 'django.middleware.common.CommonMiddleware',
  4. 'django.middleware.cache.FetchFromCacheMiddleware',
  5. ]

Note

No, that's not a typo: the "update" middleware must be first in the list,and the "fetch" middleware must be last. The details are a bit obscure, butsee Order of MIDDLEWARE below if you'd like the full story.

Then, add the following required settings to your Django settings file:

  • CACHE_MIDDLEWARE_ALIAS — The cache alias to use for storage.
  • CACHE_MIDDLEWARE_SECONDS — The number of seconds each page shouldbe cached.
  • CACHE_MIDDLEWARE_KEY_PREFIX — If the cache is shared acrossmultiple sites using the same Django installation, set this to the name ofthe site, or some other string that is unique to this Django instance, toprevent key collisions. Use an empty string if you don't care.FetchFromCacheMiddleware caches GET and HEAD responses with status 200,where the request and response headers allow. Responses to requests for the sameURL with different query parameters are considered to be unique pages and arecached separately. This middleware expects that a HEAD request is answered withthe same response headers as the corresponding GET request; in which case it canreturn a cached GET response for HEAD request.

Additionally, UpdateCacheMiddleware automatically sets a few headers in eachHttpResponse:

  • Sets the Expires header to the current date/time plus the definedCACHE_MIDDLEWARE_SECONDS.
  • Sets the Cache-Control header to give a max age for the page —again, from the CACHE_MIDDLEWARE_SECONDS setting.Changed in Django 1.11:In older versions, the Last-Modified header was also set.

See 中间件 for more on middleware.

If a view sets its own cache expiry time (i.e. it has a max-age section inits Cache-Control header) then the page will be cached until the expirytime, rather than CACHE_MIDDLEWARE_SECONDS. Using the decorators indjango.views.decorators.cache you can easily set a view's expiry time(using the cache_control() decorator) ordisable caching for a view (using thenever_cache() decorator). See theusing other headers section for more on these decorators.

If USE_I18N is set to True then the generated cache key willinclude the name of the active language — see alsoHow Django discovers language preference). This allows you to easilycache multilingual sites without having to create the cache key yourself.

Cache keys also include the active language whenUSE_L10N is set to True and the current time zone when USE_TZ is set to True.

The per-view cache

  • django.views.decorators.cache.cache_page()
  • A more granular way to use the caching framework is by caching the output ofindividual views. django.views.decorators.cache defines a cache_pagedecorator that will automatically cache the view's response for you. It's easyto use:
  1. from django.views.decorators.cache import cache_page
  2.  
  3. @cache_page(60 * 15)
  4. def my_view(request):
  5. ...

cache_page takes a single argument: the cache timeout, in seconds. In theabove example, the result of the my_view() view will be cached for 15minutes. (Note that we've written it as 60 15 for the purpose ofreadability. 60 15 will be evaluated to 900 — that is, 15 minutesmultiplied by 60 seconds per minute.)

The per-view cache, like the per-site cache, is keyed off of the URL. Ifmultiple URLs point at the same view, each URL will be cached separately.Continuing the my_view example, if your URLconf looks like this:

  1. urlpatterns = [
  2. path('foo/<int:code>/', my_view),
  3. ]

then requests to /foo/1/ and /foo/23/ will be cached separately, asyou may expect. But once a particular URL (e.g., /foo/23/) has beenrequested, subsequent requests to that URL will use the cache.

cache_page can also take an optional keyword argument, cache,which directs the decorator to use a specific cache (from yourCACHES setting) when caching view results. By default, thedefault cache will be used, but you can specify any cache youwant:

  1. @cache_page(60 * 15, cache="special_cache")def my_view(request):

You can also override the cache prefix on a per-view basis. cache_pagetakes an optional keyword argument, key_prefix,which works in the same way as the CACHE_MIDDLEWARE_KEY_PREFIXsetting for the middleware. It can be used like this:

  1. @cache_page(60 * 15, key_prefix="site1")def my_view(request):

The key_prefix and cache arguments may be specified together. Thekey_prefix argument and the KEY_PREFIXspecified under CACHES will be concatenated.

Specifying per-view cache in the URLconf

The examples in the previous section have hard-coded the fact that the view iscached, because cache_page alters the my_view function in place. Thisapproach couples your view to the cache system, which is not ideal for severalreasons. 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 mightwant to use them without being cached. The solution to these problems is tospecify the per-view cache in the URLconf rather than next to the view functionsthemselves.

Doing so is easy: simply wrap the view function with cache_page when yourefer to it in the URLconf. Here's the old URLconf from earlier:

  1. urlpatterns = [
  2. path('foo/<int:code>/', my_view),
  3. ]

Here's the same thing, with my_view wrapped in cache_page:

  1. from django.views.decorators.cache import cache_page
  2.  
  3. urlpatterns = [
  4. path('foo/<int:code>/', cache_page(60 * 15)(my_view)),
  5. ]

Template fragment caching

If you're after even more control, you can also cache template fragments usingthe cache template tag. To give your template access to this tag, put{% load cache %} near the top of your template.

The {% cache %} template tag caches the contents of the block for a givenamount of time. It takes at least two arguments: the cache timeout, in seconds,and the name to give the cache fragment. The fragment is cached forever iftimeout is None. The name will be taken as is, do not use a variable. Forexample:

  1. {% load cache %}
  2. {% cache 500 sidebar %}
  3. .. sidebar ..
  4. {% endcache %}

Changed in Django 2.0:Older versions don't allow a None timeout.

Sometimes you might want to cache multiple copies of a fragment depending onsome dynamic data that appears inside the fragment. For example, you might want aseparate cached copy of the sidebar used in the previous example for every userof your site. Do this by passing one or more additional arguments, which may bevariables with or without filters, to the {% cache %} template tag touniquely identify the cache fragment:

  1. {% load cache %}
  2. {% cache 500 sidebar request.user.username %}
  3. .. sidebar for logged in user ..
  4. {% endcache %}

If USE_I18N is set to True the per-site middleware cache willrespect the active language. For the cache templatetag you could use one of thetranslation-specific variables available intemplates to achieve the same result:

  1. {% load i18n %}
  2. {% load cache %}
  3.  
  4. {% get_current_language as LANGUAGE_CODE %}
  5.  
  6. {% cache 600 welcome LANGUAGE_CODE %}
  7. {% trans "Welcome to example.com" %}
  8. {% endcache %}

The cache timeout can be a template variable, as long as the template variableresolves to an integer value. For example, if the template variablemy_timeout is set to the value 600, then the following two examples areequivalent:

  1. {% cache 600 sidebar %} ... {% endcache %}
  2. {% cache my_timeout sidebar %} ... {% endcache %}

This feature is useful in avoiding repetition in templates. You can set thetimeout in a variable, in one place, and just reuse that value.

By default, the cache tag will try to use the cache called "template_fragments".If no such cache exists, it will fall back to using the default cache. You mayselect an alternate cache backend to use with the using keyword argument,which must be the last argument to the tag.

  1. {% cache 300 local-thing ... using="localcache" %}

It is considered an error to specify a cache name that is not configured.

  • django.core.cache.utils.maketemplate_fragment_key(_fragment_name, vary_on=None)
  • If you want to obtain the cache key used for a cached fragment, you can usemake_template_fragment_key. fragment_name is the same as second argumentto the cache template tag; vary_on is a list of all additional argumentspassed to the tag. This function can be useful for invalidating or overwritinga cached item, for example:
  1. >>> from django.core.cache import cache
  2. >>> from django.core.cache.utils import make_template_fragment_key
  3. # cache key for {% cache 500 sidebar username %}
  4. >>> key = make_template_fragment_key('sidebar', [username])
  5. >>> cache.delete(key) # invalidates cached template fragment

The low-level cache API

Sometimes, caching an entire rendered page doesn't gain you very much and is,in fact, inconvenient overkill.

Perhaps, for instance, your site includes a view whose results depend onseveral 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 theper-site or per-view cache strategies offer, because you wouldn't want tocache the entire result (since some of the data changes often), but you'd stillwant to cache the results that rarely change.

For cases like this, Django exposes a simple, low-level cache API. You can usethis 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 objectscan be pickled; refer to the Python documentation for more information aboutpickling.)

Accessing the cache

  • django.core.cache.caches
  • You can access the caches configured in the CACHES settingthrough a dict-like object: django.core.cache.caches. Repeatedrequests for the same alias in the same thread will return the sameobject.
  1. >>> from django.core.cache import caches
  2. >>> cache1 = caches['myalias']
  3. >>> cache2 = caches['myalias']
  4. >>> cache1 is cache2
  5. True

If the named key does not exist, InvalidCacheBackendError will beraised.

To provide thread-safety, a different instance of the cache backend willbe returned for each thread.

  • django.core.cache.cache
  • As a shortcut, the default cache is available asdjango.core.cache.cache:
  1. >>> from django.core.cache import cache

This object is equivalent to caches['default'].

Basic usage

The basic interface is set(key, value, timeout) and get(key):

  1. >>> cache.set('my_key', 'hello, world!', 30)
  2. >>> cache.get('my_key')
  3. 'hello, world!'

key should be a str, and value can be any picklable Python object.

The timeout argument is optional and defaults to the timeout argumentof the appropriate backend in the CACHES setting (explained above).It's the number of seconds the value should be stored in the cache. Passing inNone for timeout will cache the value forever. A timeout of 0won't cache the value.

If the object doesn't exist in the cache, cache.get() returns None:

  1. >>> # Wait 30 seconds for 'my_key' to expire...
  2. >>> cache.get('my_key')
  3. None

We advise against storing the literal value None in the cache, because youwon't be able to distinguish between your stored None value and a cachemiss signified by a return value of None.

cache.get() can take a default argument. This specifies which value toreturn if the object doesn't exist in the cache:

  1. >>> cache.get('my_key', 'has expired')
  2. 'has expired'

To add a key only if it doesn't already exist, use the add() method.It takes the same parameters as set(), but it will not attempt toupdate the cache if the key specified is already present:

  1. >>> cache.set('add_key', 'Initial value')
  2. >>> cache.add('add_key', 'New value')
  3. >>> cache.get('add_key')
  4. 'Initial value'

If you need to know whether add() stored a value in the cache, you cancheck the return value. It will return True if the value was stored,False otherwise.

If you want to get a key's value or set a value if the key isn't in the cache,there is the get_or_set() method. It takes the same parameters as get()but the default is set as the new cache value for that key, rather than simplyreturned:

  1. >>> cache.get('my_new_key') # returns None
  2. >>> cache.get_or_set('my_new_key', 'my new value', 100)
  3. 'my new value'

You can also pass any callable as a default value:

  1. >>> import datetime
  2. >>> cache.get_or_set('some-timestamp-key', datetime.datetime.now)
  3. datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)

There's also a get_many() interface that only hits the cache once.get_many() returns a dictionary with all the keys you asked for thatactually exist in the cache (and haven't expired):

  1. >>> cache.set('a', 1)
  2. >>> cache.set('b', 2)
  3. >>> cache.set('c', 3)
  4. >>> cache.get_many(['a', 'b', 'c'])
  5. {'a': 1, 'b': 2, 'c': 3}

To set multiple values more efficiently, use set_many() to pass a dictionaryof key-value pairs:

  1. >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})
  2. >>> cache.get_many(['a', 'b', 'c'])
  3. {'a': 1, 'b': 2, 'c': 3}

Like cache.set(), set_many() takes an optional timeout parameter.

On supported backends (memcached), set_many() returns a list of keys thatfailed to be inserted.

Changed in Django 2.0:The return value containing list of failing keys was added.

You can delete keys explicitly with delete(). This is an easy way ofclearing the cache for a particular object:

  1. >>> cache.delete('a')

If you want to clear a bunch of keys at once, delete_many() can take a listof keys to be cleared:

  1. >>> cache.delete_many(['a', 'b', 'c'])

Finally, if you want to delete all the keys in the cache, usecache.clear(). Be careful with this; clear() will remove _everything_from the cache, not just the keys set by your application.

  1. >>> cache.clear()

You can also increment or decrement a key that already exists using theincr() or decr() methods, respectively. By default, the existing cachevalue will be incremented or decremented by 1. Other increment/decrement valuescan be specified by providing an argument to the increment/decrement call. AValueError will be raised if you attempt to increment or decrement anonexistent cache key.:

  1. >>> cache.set('num', 1)
  2. >>> cache.incr('num')
  3. 2
  4. >>> cache.incr('num', 10)
  5. 12
  6. >>> cache.decr('num')
  7. 11
  8. >>> cache.decr('num', 5)
  9. 6

Note

incr()/decr() methods are not guaranteed to be atomic. On thosebackends that support atomic increment/decrement (most notably, thememcached backend), increment and decrement operations will be atomic.However, if the backend doesn't natively provide an increment/decrementoperation, it will be implemented using a two-step retrieve/update.

You can close the connection to your cache with close() if implemented bythe cache backend.

  1. >>> cache.close()

Note

For caches that don't implement close methods it is a no-op.

Cache key prefixing

If you are sharing a cache instance between servers, or between yourproduction and development environments, it's possible for data cachedby one server to be used by another server. If the format of cacheddata is different between servers, this can lead to some very hard todiagnose problems.

To prevent this, Django provides the ability to prefix all cache keysused by a server. When a particular cache key is saved or retrieved,Django will automatically prefix the cache key with the value of theKEY_PREFIX cache setting.

By ensuring each Django instance has a differentKEY_PREFIX, you can ensure that there will be nocollisions in cache values.

Cache versioning

When you change running code that uses cached values, you may need topurge any existing cached values. The easiest way to do this is toflush the entire cache, but this can lead to the loss of cache valuesthat are still valid and useful.

Django provides a better way to target individual cache values.Django's cache framework has a system-wide version identifier,specified using the VERSION cache setting.The value of this setting is automatically combined with the cacheprefix and the user-provided cache key to obtain the final cache key.

By default, any key request will automatically include the sitedefault cache key version. However, the primitive cache functions allinclude a version argument, so you can specify a particular cachekey version to set or get. For example:

  1. >>> # Set version 2 of a cache key
  2. >>> cache.set('my_key', 'hello world!', version=2)
  3. >>> # Get the default version (assuming version=1)
  4. >>> cache.get('my_key')
  5. None
  6. >>> # Get version 2 of the same key
  7. >>> cache.get('my_key', version=2)
  8. 'hello world!'

The version of a specific key can be incremented and decremented usingthe incr_version() and decr_version() methods. Thisenables specific keys to be bumped to a new version, leaving otherkeys unaffected. Continuing our previous example:

  1. >>> # Increment the version of 'my_key'
  2. >>> cache.incr_version('my_key')
  3. >>> # The default version still isn't available
  4. >>> cache.get('my_key')
  5. None
  6. # Version 2 isn't available, either
  7. >>> cache.get('my_key', version=2)
  8. None
  9. >>> # But version 3 *is* available
  10. >>> cache.get('my_key', version=3)
  11. 'hello world!'

Cache key transformation

As described in the previous two sections, the cache key provided by auser is not used verbatim — it is combined with the cache prefix andkey version to provide a final cache key. By default, the three partsare joined using colons to produce a final string:

  1. def make_key(key, key_prefix, version):
  2. return ':'.join([key_prefix, str(version), key])

If you want to combine the parts in different ways, or apply otherprocessing to the final key (e.g., taking a hash digest of the keyparts), you can provide a custom key function.

The KEY_FUNCTION cache settingspecifies a dotted-path to a function matching the prototype ofmake_key() above. If provided, this custom key function willbe used instead of the default key combining function.

Cache key warnings

Memcached, the most commonly-used production cache backend, does not allowcache keys longer than 250 characters or containing whitespace or controlcharacters, and using such keys will cause an exception. To encouragecache-portable code and minimize unpleasant surprises, the other built-in cachebackends issue a warning (django.core.cache.backends.base.CacheKeyWarning)if a key is used that would cause an error on memcached.

If you are using a production backend that can accept a wider range of keys (acustom backend, or one of the non-memcached built-in backends), and want to usethis wider range without warnings, you can silence CacheKeyWarning withthis code in the management module of one of yourINSTALLED_APPS:

  1. import warnings
  2.  
  3. from django.core.cache import CacheKeyWarning
  4.  
  5. warnings.simplefilter("ignore", CacheKeyWarning)

If you want to instead provide custom key validation logic for one of thebuilt-in backends, you can subclass it, override just the validate_keymethod, and follow the instructions for using a custom cache backend. Forinstance, to do this for the locmem backend, put this code in a module:

  1. from django.core.cache.backends.locmem import LocMemCache
  2.  
  3. class CustomLocMemCache(LocMemCache):
  4. def validate_key(self, key):
  5. """Custom validation, raising exceptions or warnings as needed."""
  6. ...

…and use the dotted Python path to this class in theBACKEND portion of your CACHES setting.

下游缓存

到目前为止,该文档主要关注缓存自己的数据。但另一种类型的缓存也与 Web 开发相关:缓存由“下游”缓存执行。这些系统甚至在请求到达您的网站之前为用户缓存页面。

下面是一些下游缓存的例子:

  • 您的 ISP 可能会缓存某些页面,因此如果您从 https://example.com/ 请求页面,您的 ISP 将直接向您发送页面,而不必直接访问 example.com。example.com 的维护者对这个缓存一无所知;ISP 位于 example.com 和 Web 浏览器之间,透明地处理所有缓存。
  • 您的 Django 网站可能会在一个代理缓存的后面,例如Squid 网页代理缓存(http://www.squid-cache.org/),为了性能而缓存页面。在这种情况下,每个请求首先由代理来处理,只有在需要时才将其传递给应用程序。
  • 你的网页浏览器也会缓存页面。如果 Web 页面发送了适当的请求头,浏览器将使用本地缓存的副本来对该页面进行后续请求,而不必再次与 Web 页面联系以查看它是否已经更改。下游缓存是一个很好的效率提升,但是它有一个危险:许多网页的内容基于认证和其他变量的不同而不同,而纯粹基于 URL 的盲目保存页面的缓存系统可能会将不正确或敏感的数据暴露给那些页面的后续访问者。

比如说,你操作一个网络电子邮件系统,“收件箱”页面的内容显然取决于哪个用户登录。如果 ISP 盲目缓存您的站点,那么通过 ISP 登录的第一个用户将为随后的访问者缓存其特定于用户的收件箱页面。那就不妙了。

幸运的是,HTTP 为这个问题提供了解决方案。存在许多 HTTP 报头以指示下游缓存根据指定的变量来区分它们的缓存内容,并且告诉缓存机制不缓存特定的页面。我们将在下面的章节中查看这些标题。

使用 Vary 标头

“可变”标头定义了缓存机制在构建其缓存密钥时应考虑哪些请求报头。例如,如果网页的内容取决于用户的语言偏好,则该页面被称为“在语言上有所不同”。

默认情况下,Django 的缓存系统使用请求的完全合格的URL创建它的缓存密钥——例如,"https://www.example.com/stories/2005/?order_by=author&#34;。这意味着对该 URL 的每个请求都将使用相同的缓存版本,而不管用户代理差异(如 cookies 或语言首选项)。但是,如果这个页面基于请求头(如 cookie、语言或用户代理)中的某些差异而产生不同的内容,则需要使用Vary 标头来告诉缓存机制,页面输出取决于这些东西。

To do this in Django, use the convenientdjango.views.decorators.vary.vary_on_headers() view decorator, like so:

  1. from django.views.decorators.vary import vary_on_headers
  2.  
  3. @vary_on_headers('User-Agent')
  4. def my_view(request):
  5. ...

In this case, a caching mechanism (such as Django's own cache middleware) willcache a separate version of the page for each unique user-agent.

The advantage to using the varyon_headers decorator rather than manuallysetting the Vary header (using something likeresponse['Vary'] = 'user-agent') is that the decorator _adds to theVary header (which may already exist), rather than setting it from scratchand potentially overriding anything that was already in there.

You can pass multiple headers to vary_on_headers():

  1. @vary_on_headers('User-Agent', 'Cookie')def my_view(request):

This tells downstream caches to vary on both, which means each combination ofuser-agent and cookie will get its own cache value. For example, a request withthe user-agent Mozilla and the cookie value foo=bar will be considereddifferent from a request with the user-agent Mozilla and the cookie valuefoo=ham.

Because varying on cookie is so common, there's adjango.views.decorators.vary.vary_on_cookie() decorator. These two viewsare equivalent:

  1. @vary_on_cookiedef my_view(request):

  2. @vary_on_headers('Cookie')def my_view(request):

The headers you pass to vary_on_headers are not case sensitive;"User-Agent" is the same thing as "user-agent".

You can also use a helper function, django.utils.cache.patch_vary_headers(),directly. This function sets, or adds to, the Vary header. For example:

  1. from django.shortcuts import render
  2. from django.utils.cache import patch_vary_headers
  3.  
  4. def my_view(request):
  5. ...
  6. response = render(request, 'template_name', context)
  7. patch_vary_headers(response, ['Cookie'])
  8. return response

patch_vary_headers takes an HttpResponse instance asits first argument and a list/tuple of case-insensitive header names as itssecond argument.

For more on Vary headers, see the official Vary spec.

使用其他标头控制高速缓存

缓存的其他问题是数据的隐私和数据应该存储在缓存的级联中的问题。

用户通常面临两种缓存:它们自己的浏览器缓存(私有缓存)和它们的提供者的缓存(公共缓存)。公共缓存由多个用户使用,并由其他用户控制。这给敏感数据带来了问题——你不希望,比如说,你的银行帐号存储在一个公共缓存中。因此,Web 应用程序需要一种方法来告诉缓存数据是私有的,哪些是公开的。

解决方案是指出一个页面的缓存应该是“私有的”。在 Django中,使用 cache_control() 。例子:

  1. from django.views.decorators.cache import cache_control
  2.  
  3. @cache_control(private=True)
  4. def my_view(request):
  5. ...

这个装饰器负责在场景后面发送适当的 HTTP 头。

注意,缓存控制设置“私有”和“公共”是互斥的。装饰器确保“公共”指令被移除,如果应该设置“私有”(反之亦然)。这两个指令的一个示例使用将是一个提供私人和公共条目的博客站点。公共条目可以缓存在任何共享缓存上。下面的代码使用 patch_cache_control(),手动修改缓存控制头的方法(内部调用的是 cache_control() 装饰器):

  1. from django.views.decorators.cache import patch_cache_control
  2. from django.views.decorators.vary import vary_on_cookie
  3.  
  4. @vary_on_cookie
  5. def list_blog_entries_view(request):
  6. if request.user.is_anonymous:
  7. response = render_only_public_entries()
  8. patch_cache_control(response, public=True)
  9. else:
  10. response = render_private_and_public_entries(request.user)
  11. patch_cache_control(response, private=True)
  12.  
  13. return response

You can control downstream caches in other ways as well (see RFC 7234 fordetails on HTTP caching). For example, even if you don't use Django'sserver-side cache framework, you can still tell clients to cache a view for acertain amount of time with the max-agedirective:

  1. from django.views.decorators.cache import cache_control
  2.  
  3. @cache_control(max_age=3600)
  4. def my_view(request):
  5. ...

(If you do use the caching middleware, it already sets the max-age withthe value of the CACHE_MIDDLEWARE_SECONDS setting. In that case,the custom max_age from thecache_control() decorator will takeprecedence, and the header values will be merged correctly.)

Any valid Cache-Control response directive is valid in cache_control().Here are some more examples:

  • no_transform=True
  • must_revalidate=True
  • stale_while_revalidate=num_secondsThe full list of known directives can be found in the IANA registry(note that not all of them apply to responses).

If you want to use headers to disable caching altogether,never_cache() is a view decorator thatadds headers to ensure the response won't be cached by browsers or othercaches. Example:

  1. from django.views.decorators.cache import never_cache
  2.  
  3. @never_cache
  4. def myview(request):
  5. ...

MIDDLEWARE顺序

如果使用缓存中间件,重要的是将每一半放在 MIDDLEWARE 设置的正确位置。这是因为缓存中间件需要知道哪些头可以改变缓存存储。中间件总是可以在 Vary 响应头中添加一些东西。

UpdateCacheMiddleware 在响应阶段运行,其中中间件以相反的顺序运行,因此列表顶部的项目在响应阶段的最后运行。因此,您需要确保 UpdateCacheMiddleware 出现在任何其他可能添加到 Vary 标头的其他中间件之前。下面的中间件模块类似:

  • SessionMiddleware 添加 Cookie
  • GZipMiddleware 添加 Accept-Encoding
  • LocaleMiddleware 添加 Accept-LanguageFetchFromCacheMiddleware, on the other hand, runs during the request phase,where middleware is applied first-to-last, so an item at the top of the listruns first during the request phase. The FetchFromCacheMiddleware alsoneeds to run after other middleware updates the Vary header, soFetchFromCacheMiddleware must be after any item that does so.