Paul D. Waite
Paul D. Waite

Reputation: 98906

Can I stop Django’s site-wide caching MiddleWare from setting Cache-Control and Expires to the same values that memcached uses?

I’m setting up a Django site to use memcached, via Django’s site-wide caching MiddleWare.

I planned to store pages in memcached for a very long time (because they don’t change very often, and because my whole site should comfortably fit into a relatively small amount of memory), and amend my code to delete pages from memcached when the data on those pages does change (to avoid stale pages).

However, Django’s MiddleWare sets the Cache-Control and Expires HTTP headers on its responses to the same values that memcached uses for its expiry policy. That means that if I set a very long expiry for cached pages in memcached, end users’ browsers will use that expiry too, making them more likely to get stale data.

Can I stop Django’s MiddleWare from doing this?

Upvotes: 1

Views: 1435

Answers (3)

saul.shanabrook
saul.shanabrook

Reputation: 3168

I recently created django-response-timeout to solve this problem on a site-wide basis. It will add the max_age header to all views as well as the expiry time. To install pip install django-response-timeout. Then add response_timeout.middleware.SetCacheTimeoutMiddleware to your middleware like so:

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'response_timeout.middleware.SetCacheTimeoutMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)

Finally set RESPONSE_CACHE_SECONDS to however long you want responses to be cached.

Upvotes: 0

nagisa
nagisa

Reputation: 720

You can add

@cache_control(must_revalidate=True, max_age=3600)

decorator to each of your views to make browsers validate their cache contents every time page is loaded. It is available by importing

from django.views.decorators.cache import cache_control

After that, if content on server is changed, then browser will redownload page from server.

Upvotes: 4

dMb
dMb

Reputation: 9367

Django docs have a whole page on caching. Is that not providing you with information you need?

Specifically:

There are a few other ways to control cache parameters. For example, HTTP allows applications to do the following:

Define the maximum time a page should be cached. Specify whether a cache should always check for newer versions, only delivering the cached content when there are no changes. (Some caches might deliver cached content even if the server page changed, simply because the cache copy isn't yet expired.)

Upvotes: -1

Related Questions