O framework de “cache” do Django

Um dos pontos de perda de equilíbrio em websites dinâmicos, bom, é que eles são dinâmicos. Cada vez que um usuário requisita uma página, o servidor Web faz todo tipo de cálculo – de consultas de bancos de dados para renderização de templates à lógica de negócios – para criar páginas que seus visitantes vêem. Visto de uma perspectiva de processamento, isso é muito mais caro, do que uma leitura padrão no sistema de arquivos organizado em um servidor.

Para a maioria das aplicações Web, esta carga d processamento não é grande coisa. A maioria dos aplicativos não são um washingtonpost.com ou slashdot.org; eles são sites simples de tamanho pequenos a médios com tráfego razoável. Mas para site com tráfego de média a alto, é essencial cortar o máximo de processamento.

É aqui que o “cache” entra.

“Cachear” alguma coisa é guardar o resultado de um cálculo caro para que você não tenha que realziar o cálculo uma próxima vez. Aqui um pseduo-código explicando como isso funcionaria para uma página Web gerada dinamicamente.

given a URL, try finding that page in the cache
if the page is in the cache:
    return the cached page
else:
    generate the page
    save the generated page in the cache (for next time)
    return the generated page

Django vem com um sistema de cache robusto que lhe dexa salvar páginas dinâmicas para que não tenham que ser calculadas para cada requisição. Por conveniência, o Django oferece diferentes níveis de granulação do cache: Você pode cachear a saída de uma determinada “view” ,você pode cachear somente os pedaços que estão diciceis de produzir, ou você pode cachear seu site inteiro.

Django também trabalha bem com caches processados fora do Djanfo, tal como Squid e caches baseados em navegadores. Estes são tipo de cache que o desenvolvedor não controla diretamente mas para os quais você pode providenciar dicas (através de cabeçalhos HTTP) sobre quais partes do seu site devem ser cacheadas, e como.

Ver também

A A filosofia de construção do frameowrk de cache explica um pouco das decisões de desenho do framework.

Definindo o cache.

O sistema de cache requer um número pequeno de definições. Listando, você deve dizer onde seus dados de cache devem ficar – se na base de dados, no sistema de arquivos ou diretamente em memória. Essa é uma decisão importante que afeta a performance do seu cache; e sim, alguns tipode de cache são mais rápidos que outros.

Suas preferências de “cache” vão na definição CACHES do seu arquivo de definições. Aqui uma explicação de todos os valores possíveis para o CACHES.

Memcached

O mais rápido, mais eficiente tipo de cache suportado nativamente pelo Django, Memcached é um servidor de cache totalmente baseado em memória, originalmente desenvolvido para lidar com altas cargas no LiveJournal.com e subsequentemente teve seu código aberto pela Danga Interactive. É usado por sites como Facebook e Wikipedia para reduzir acesso ao banco de dados e melhora a performance do site dramaticamente

O memcached é executado como um serviço e aloca um montante de RAM. Tudo o que ele faz é adicionar, recuperar e deletar dados no cache. Todo o dado é armazenado diretamente em memória, então não há custo de acesso ao banco de dados ou ao sistema de arquivos.

Depois de instalar o próprio memcached , você irá precisar instalar o uma lib para acesso ao Memcached. Existem várias bibliotecas Memcached de acesso para Python; as duas mais comuns são python-memcached e pylibmc.

Para usar o Memcached com o Django:

  • Defina o BACKEND para django.core.cache.backends.memcached.MemcachedCache ou django.core.cache.backends.memcached.PyLibMCCache (dependendo do que você escolheu com biblioteca de acesso ao Memcached)

  • Defina o LOCATION para os valores de ip:port, onde ip é o endereço IP do serviço do Memcached e port é a porta na quam o Memcached está rodando, ou para um valor de unix:path, onde o path é o caminho para o arquivo de Socket Unix do Memcached.

Neste exemplo, o Memcached está rodando no localhost(127.0.0.1) porta 11211, usando a biblioteca de acesso python-memcached:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

Neste exemplo, o Memcached está disponível através de um arquivo socket Unix local /tmp/memcached.sock usando a biblioteca de acesso python-memcached:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': 'unix:/tmp/memcached.sock',
    }
}

Quando usar a biblioteca de acesso pylibmc, não inclua o prefixo unix:/:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': '/tmp/memcached.sock',
    }
}

Uma característica excelente do Memcached é sua habilidade de compartilhar o cache em servidores múltiplos. Isso significa que você pode rodar o serviço do Memcached em múltiplas máquinas, e o programa irá tratar o grupo de máquinas como um único cache, sem a necessidade de duplicar valores no cache de cada máquina. Para aproveitar essa característica, inclua todos os endereços dos servidores no setting:LOCATION <CACHES-LOCATION>, separados por uma vírgula ou como uma lista.

Neste exemplo, o cache é compartilhado em instâncias de Memcached rodando nos endereços IP 172.19.26.240 e 172.19.26.242, ambos na porta 11211:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': [
            '172.19.26.240:11211',
            '172.19.26.242:11211',
        ]
    }
}

No exemplo seguinte, o cache está compartilhado nas instâncias de Memcached rodando nos endereços IP 172.19.26.240 (porta 11211), 172.19.26.242 (porta 11212), e 172.19.26.244 (porta 11213):

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': [
            '172.19.26.240:11211',
            '172.19.26.242:11212',
            '172.19.26.244:11213',
        ]
    }
}

Um último ponto sobre o Memcached é que o cache baseado em memória tem desvantagem: como o dado cacheado é armazenado em memória, os dados serão perdidos se seu servidor cair. Claramente, a memória não é feita para armazenar dados de maneira permanente, então não conte com cache baseado em memória como seu único armazenamento de dados. Sem dúvida, nenhum dos “backends” de cache do Django devem ser usados para armazenamento permanente – eles são todos feitos para solução de cache e não armazenamento – mas colocamos isso aqui porque o cache baseado em memória é temporário.

Cache no Banco de Dados

O Django pode armazenar seus dados de cache em um banco de dados. Isso funciona melhor se você tem um servidor de banco de dados rápido e bem indexado.

Para usar uma tabela de banco de dados como seu “backend” de cache:

  • Defina o BACKEND como django.core.cache.backends.db.DatabaseCache

  • Defina o LOCATION indicando o tablename, o nome da tabela do banco de dados. Este nome pode ser o que você quiser, com tanto que seja um nome de tabela válido e que não esteja sendo usado em seu banco de dados.

Neste exemplo, o nome da tabela de cache é my_cache_table:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

Criando a tabela de cache

Antes de usar o cache no banco de dados, você deve criar a tabela de cache com este comando:

python manage.py createcachetable

Isso cria uma tabela no seu banco de dados que tem o formato correto que o sistema de cache do Django para cache em banco de dados precisa. O nome da tabela é pego da definição de LOCATION.

Se estiver usando caches em múltiplos banco de dados, o createcachetable cria uma tabela para cada cache.

Se estiver usando múltiplas bases de dados, o createcachetable verifica o método allow_migrate() dos seus roteadores de banco de dados (veja abaixo).

Assim como o migrate, createcachetable não irá tocar nenhuma tabela já existente. Somente criará as tabelas faltantes.

Para ver o SQL que deve se executado, ao invés de executá-lo, use a opção createcachetable --dry-run.

Múltiplos bancos de dados

Se você está usando “cache” no banco de dados com múltiplos bancos de dados, você também precisará definir instruções de roteamento para sua tabela de “cache” no banco de dados. Para propósitos de roteamento, a tabela de “cache” no banco de dados aparece como um modelo chamado CacheEntry, em uma aplicação chamada django_cache. Este modelo não aparecerá no cache dos modelos, mas o detalhes do modelo podem ser usado para propósitos de roteamento.

Por exemplo, o roteador a seguir, direciona todas as operações de leitura de cache para cache_replica, e todas as operações de escrita para cache_primary. A tabela de cache somente será sincronizada dentro de cache_primary:

class CacheRouter(object):
    """A router to control all database cache operations"""

    def db_for_read(self, model, **hints):
        "All cache read operations go to the replica"
        if model._meta.app_label == 'django_cache':
            return 'cache_replica'
        return None

    def db_for_write(self, model, **hints):
        "All cache write operations go to primary"
        if model._meta.app_label == 'django_cache':
            return 'cache_primary'
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        "Only install the cache model on primary"
        if app_label == 'django_cache':
            return db == 'cache_primary'
        return None

Se você não especificar direções de rotas para o modelo de cache do banco de dados, o “backend” de cache usará o banco de dados padrão.

Claro que, se você não usa o “backend” de cache de banco de dados, você não precisa se preocupar sobre fornecer instruções de rotas para o modelo de cache do banco de dados.

Cache no sistema de arquivos

O backend baseado em arquivo serializa e armazena cada valor do cache como um arquivo separado. Para usar este backend defina BACKEND como "django.core.cache.backends.filebased.FileBasedCache" e LOCATION <CACHES-LOCATION>`para o diretório adequado. Por exemplo, para armazenar dados de cache em `/var/tmp/django_cache``, use esta definição:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
}

Se estiver no windows, coloque a letra do disco no começo do caminha, assim:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': 'c:/foo/bar',
    }
}

O caminho do diretório deve ser absotluto – quer dizer, ele deve começar na raiz do seu sistema de arquivos. Não importa se você coloca uma barra no final da definição.

Assegure-se que o diretório apontado por esta definição existe e se o usuário do sistema que executa o servidor web tem permissão de leitura e escrita. Continuando o exemplo acima, se o usuário que executa seu servidor se chama apache, assegure-se que o diretório /var/tmp/django_cache existe e pode ser lido e escrito pelo usuário apache.

Cache em memória local

Este é o cache padrão se não houver outro especificado no arquivo de configurações. Se você quer a vantagem de velocidade do cache em memória mas não tem a capacidade de rodar o Memcached, considere o backend para cache em memória local. Este cache é um cache por processo (veja abaixo) e seguro entre “threads”. Para usá-lo, defina BACKEND com "django.core.cache.backends.locmem.LocMemCache". Por exemplo:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

O LOCATION do cache é usado para identificar armazenamentos individuais em memória is. Se você tem somente um cache locmem, você pode omitir o LOCATION; no entanto, se você tiver mais de um cache em memória, você precisa definir um nome para pelo menos um deles de modo a mantê-los separados.

Note que cada processo terá sua própria instância de cache, o que significa que não é possível processos compartilharem o cache. Isso também significa não é particularmente eficiente quanto a memória, então provavelmente não é uma boa escolha para um ambiente de produção. É bom para desenvolvimento.

Cache fictício (para desenvolvimento)

Finalmente, o Django traz um cache “fictício” que não realiza o cache realmente – somente implementa a interface de cache sem fazer mais nada.

É útil se você tem um ambiente de produção que faz usa pesado de cache em vários lugares menos em um ambiente de desenvolvimento ou teste onde você não quer o cache e não quer alterar seu código para tal. Para ativar o cache fictício, defina a BACKEND como abaixo:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

Usando um esquema de cache personalizado

Embora o Django já tenha suporte para vários mecanismos de “cache”, as vezes você quer usar um mecanismo personalizado. Para usar um mecanismo de “cache” externo, use o caminho de importação do Python como no BACKEND da definição do CACHES, como a seguir:

CACHES = {
    'default': {
        'BACKEND': 'path.to.backend',
    }
}

Se você estiver construindo seu próprio mecanismo, você pode usar as implementações padrão de mecanismo de cache como referência. Você achará o código no diretório django/core/cache/backends/ do código fonte do Django.

Nota: se não tiver uma noa razão, tal como um servidor que não os suporta, você deveria ficar com os mecanismos de “cache” já inclusos no Django. Eles foram bem testados e são fáceis de usar.

Argumentos do cache

Each cache backend can be given additional arguments to control caching behavior. These arguments are provided as additional keys in the CACHES setting. Valid arguments are as follows:

  • TIMEOUT: The default timeout, in seconds, 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 never expire. A value of 0 causes keys to immediately expire (effectively “don’t cache”).

  • OPTIONS: 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.

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

    • MAX_ENTRIES: The maximum number of entries allowed in the cache before old values are deleted. This argument defaults to 300.

    • CULL_FREQUENCY: The fraction of entries that are culled when MAX_ENTRIES is reached. The actual ratio is 1 / CULL_FREQUENCY, so set CULL_FREQUENCY to 2 to cull half the entries when MAX_ENTRIES is reached. This argument should be an integer and defaults to 3.

      A value of 0 for CULL_FREQUENCY means that the entire 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.

  • KEY_PREFIX: A string that will be automatically included (prepended by default) to all cache keys used by the Django server.

    See the cache documentation for more information.

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

    See the cache documentation for more information.

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

    See the cache documentation for more information.

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

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
        'TIMEOUT': 60,
        'OPTIONS': {
            'MAX_ENTRIES': 1000
        }
    }
}

Invalid arguments are silently ignored, as are invalid values of known arguments.

The per-site cache

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

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
]

Nota

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, but see Order of MIDDLEWARE below if you’d like the full story.

Então, adicione as seguintes definições obrigatórias ao seu arquivo de definições Django:

  • CACHE_MIDDLEWARE_ALIAS – O apelido do cache para ser usado para armazenamento.

  • CACHE_MIDDLEWARE_SECONDS – O número em segundos que cada página deve permanecer cacheada.

  • CACHE_MIDDLEWARE_KEY_PREFIX – 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’t care.

FetchFromCacheMiddleware 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.

Additionally, UpdateCacheMiddleware automatically sets a few headers in each HttpResponse:

  • Sets the Last-Modified header to the current date/time when a fresh (not cached) version of the page is requested.
  • Sets the Expires header to the current date/time plus the defined CACHE_MIDDLEWARE_SECONDS.
  • Sets the Cache-Control header to give a max age for the page – again, from the CACHE_MIDDLEWARE_SECONDS setting.

See Middleware for more on middleware.

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

If USE_I18N is set to True then the generated cache key will include the name of the active language – see also How Django discovers language preference). This allows you to easily cache multilingual sites without having to create the cache key yourself.

Cache keys also include the active language when USE_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 of individual views. django.views.decorators.cache defines a cache_page decorator that will automatically cache the view’s response for you. It’s easy to use:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def my_view(request):
    ...

cache_page takes a single argument: the cache timeout, in seconds. In the above example, the result of the my_view() view will be cached for 15 minutes. (Note that we’ve written it as 60 * 15 for the purpose of readability. 60 * 15 will be evaluated to 900 – that is, 15 minutes multiplied by 60 seconds per minute.)

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 my_view example, if your URLconf looks like this:

urlpatterns = [
    url(r'^foo/([0-9]{1,2})/$', my_view),
]

then requests to /foo/1/ and /foo/23/ will be cached separately, as you may expect. But once a particular URL (e.g., /foo/23/) has been requested, 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 your CACHES setting) when caching view results. By default, the default cache will be used, but you can specify any cache you want:

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

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

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

The key_prefix and cache arguments may be specified together. The key_prefix argument and the KEY_PREFIX specified 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 is cached, because cache_page alters the my_view 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.

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

urlpatterns = [
    url(r'^foo/([0-9]{1,2})/$', my_view),
]

Aqui é a mesma coisa, com my_view empacotado em cache_page:

from django.views.decorators.cache import cache_page

urlpatterns = [
    url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
]

Template fragment caching

If you’re after even more control, you can also cache template fragments using the 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 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:

{% load cache %}
{% cache 500 sidebar %}
    .. sidebar ..
{% endcache %}

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 {% cache %} template tag to uniquely identify the cache fragment:

{% load cache %}
{% cache 500 sidebar request.user.username %}
    .. sidebar for logged in user ..
{% endcache %}

It’s perfectly fine to specify more than one argument to identify the fragment. Simply pass as many arguments to {% cache %} as you need.

If USE_I18N is set to True the per-site middleware cache will respect the active language. For the cache template tag you could use one of the translation-specific variables available in templates to achieve the same result:

{% load i18n %}
{% load cache %}

{% get_current_language as LANGUAGE_CODE %}

{% cache 600 welcome LANGUAGE_CODE %}
    {% trans "Welcome to example.com" %}
{% endcache %}

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 my_timeout is set to the value 600, then the following two examples are equivalent:

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

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.

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 may select an alternate cache backend to use with the using keyword argument, which must be the last argument to the tag.

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

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

django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None)

If you want to obtain the cache key used for a cached fragment, you can use make_template_fragment_key. fragment_name is the same as second argument to the cache template tag; vary_on 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:

>>> from django.core.cache import cache
>>> from django.core.cache.utils import make_template_fragment_key
# cache key for {% cache 500 sidebar username %}
>>> key = make_template_fragment_key('sidebar', [username])
>>> 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 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’t want to cache the entire result (since some of the data changes often), but you’d still want to cache the results that rarely change.

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.)

Accessing the cache

django.core.cache.caches

You can access the caches configured in the CACHES setting through a dict-like object: django.core.cache.caches. Repeated requests for the same alias in the same thread will return the same object.

>>> from django.core.cache import caches
>>> cache1 = caches['myalias']
>>> cache2 = caches['myalias']
>>> cache1 is cache2
True

If the named key does not exist, InvalidCacheBackendError will be raised.

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

django.core.cache.cache

As a shortcut, the default cache is available as django.core.cache.cache:

>>> 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):

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

key should be a str (or unicode on Python 2), and value can be any picklable Python object.

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

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

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

We advise against storing the literal value None in the cache, because you won’t be able to distinguish between your stored None value and a cache miss signified by a return value of None.

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

>>> cache.get('my_key', 'has expired')
'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 to update the cache if the key specified is already present:

>>> cache.set('add_key', 'Initial value')
>>> cache.add('add_key', 'New value')
>>> cache.get('add_key')
'Initial value'

If you need to know whether add() stored a value in the cache, you can check 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 simply returned:

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

You can also pass any callable as a default value:

>>> import datetime
>>> cache.get_or_set('some-timestamp-key', datetime.datetime.now)
datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)
Changed in Django 1.9:

The get_or_set() method was added.

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 that actually exist in the cache (and haven’t expired):

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

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

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

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

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

>>> cache.delete('a')

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

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

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

>>> cache.clear()

You can also increment or decrement a key that already exists using the incr() or decr() 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.:

>>> cache.set('num', 1)
>>> cache.incr('num')
2
>>> cache.incr('num', 10)
12
>>> cache.decr('num')
11
>>> cache.decr('num', 5)
6

Nota

incr()/decr() 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’t natively provide an increment/decrement operation, it will be implemented using a two-step retrieve/update.

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

>>> cache.close()

Nota

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 your production and development environments, it’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.

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 KEY_PREFIX cache setting.

By ensuring each Django instance has a different KEY_PREFIX, you can ensure that there will be no collisions in cache values.

Cache versioning

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.

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 cache prefix and the user-provided cache key to obtain the final cache key.

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

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

The version of a specific key can be incremented and decremented using the incr_version() and decr_version() methods. This enables specific keys to be bumped to a new version, leaving other keys unaffected. Continuing our previous example:

>>> # Increment the version of 'my_key'
>>> cache.incr_version('my_key')
>>> # The default version still isn't available
>>> cache.get('my_key')
None
# Version 2 isn't available, either
>>> cache.get('my_key', version=2)
None
>>> # But version 3 *is* available
>>> cache.get('my_key', version=3)
'hello world!'

Cache key transformation

As described in the previous two sections, the cache key provided by a user is not used verbatim – 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:

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

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.

The KEY_FUNCTION cache setting specifies a dotted-path to a function matching the prototype of make_key() above. If provided, this custom key function will be used instead of the default key combining function.

Cache key warnings

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 (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 (a custom backend, or one of the non-memcached built-in backends), and want to use this wider range without warnings, you can silence CacheKeyWarning with this code in the management module of one of your INSTALLED_APPS:

import warnings

from django.core.cache import CacheKeyWarning

warnings.simplefilter("ignore", CacheKeyWarning)

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

from django.core.cache.backends.locmem import LocMemCache

class CustomLocMemCache(LocMemCache):
    def validate_key(self, key):
        """Custom validation, raising exceptions or warnings as needed."""
        ...

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

Downstream caches

So far, this document has focused on caching your own data. But another type of caching is relevant to Web development, too: caching performed by “downstream” caches. These are systems that cache pages for users even before the request reaches your website.

Here are a few examples of downstream caches:

  • Your ISP may cache certain pages, so if you requested a page from https://example.com/, 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.
  • Your Django website may sit behind a proxy cache, such as Squid Web Proxy Cache (http://www.squid-cache.org/), 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.
  • 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.

Downstream caching is a nice efficiency boost, but there’s a danger to it: Many Web pages’ 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.

For example, say you operate a Web email system, and the contents of the “inbox” 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’s not cool.

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’ll look at some of these headers in the sections that follow.

Using Vary headers

The Vary 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’s language preference, the page is said to “vary on language.”

By default, Django’s cache system creates its cache keys using the requested fully-qualified URL – e.g., "https://www.example.com/stories/2005/?order_by=author". 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 – such as a cookie, or a language, or a user-agent – you’ll need to use the Vary header to tell caching mechanisms that the page output depends on those things.

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

from django.views.decorators.vary import vary_on_headers

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

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

The advantage to using the vary_on_headers decorator rather than manually setting the Vary header (using something like response['Vary'] = 'user-agent') is that the decorator adds to the Vary header (which may already exist), rather than setting it from scratch and potentially overriding anything that was already in there.

You can pass multiple headers to vary_on_headers():

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

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

Because varying on cookie is so common, there’s a django.views.decorators.vary.vary_on_cookie() decorator. These two views are equivalent:

@vary_on_cookie
def my_view(request):
    ...

@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:

from django.shortcuts import render
from django.utils.cache import patch_vary_headers

def my_view(request):
    ...
    response = render(request, 'template_name', context)
    patch_vary_headers(response, ['Cookie'])
    return response

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

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

Controlling cache: Using other headers

Other problems with caching are the privacy of data and the question of where data should be stored in a cascade of caches.

A user usually faces two kinds of caches: their own browser cache (a private cache) and their provider’s cache (a public cache). A public cache is used by multiple users and controlled by someone else. This poses problems with sensitive data–you don’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.

The solution is to indicate a page’s cache should be “private.” To do this in Django, use the cache_control() view decorator. Example:

from django.views.decorators.cache import cache_control

@cache_control(private=True)
def my_view(request):
    ...

This decorator takes care of sending out the appropriate HTTP header behind the scenes.

Note that the cache control settings “private” and “public” are mutually exclusive. The decorator ensures that the “public” directive is removed if “private” 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 patch_cache_control(), the manual way to modify the cache control header (it is internally called by the cache_control() decorator):

from django.views.decorators.cache import patch_cache_control
from django.views.decorators.vary import vary_on_cookie

@vary_on_cookie
def list_blog_entries_view(request):
    if request.user.is_anonymous:
        response = render_only_public_entries()
        patch_cache_control(response, public=True)
    else:
        response = render_private_and_public_entries(request.user)
        patch_cache_control(response, private=True)

    return response

You can control downstream caches in other ways as well (see RFC 7234 for details on HTTP caching). For example, even if you don’t use Django’s server-side cache framework, you can still tell clients to cache a view for a certain amount of time with the max-age directive:

from django.views.decorators.cache import cache_control

@cache_control(max_age=3600)
def my_view(request):
    ...

(If you do use the caching middleware, it already sets the max-age with the value of the CACHE_MIDDLEWARE_SECONDS setting. In that case, the custom max_age from the cache_control() decorator will take precedence, 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_seconds

The 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 that adds headers to ensure the response won’t be cached by browsers or other caches. Example:

from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
    ...

Order of MIDDLEWARE

If you use caching middleware, it’s important to put each half in the right place within the MIDDLEWARE setting. That’s because the cache middleware needs to know which headers by which to vary the cache storage. Middleware always adds something to the Vary response header when it can.

UpdateCacheMiddleware runs during the response phase, where middleware is run in reverse order, so an item at the top of the list runs last during the response phase. Thus, you need to make sure that UpdateCacheMiddleware appears before any other middleware that might add something to the Vary header. The following middleware modules do so:

  • SessionMiddleware adiciona Cookie

  • GZipMiddleware adds Accept-Encoding
  • LocaleMiddleware adds Accept-Language

FetchFromCacheMiddleware, 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 first during the request phase. The FetchFromCacheMiddleware also needs to run after other middleware updates the Vary header, so FetchFromCacheMiddleware must be after any item that does so.

Back to Top