Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fighting client-side caching in Django

Tags:

caching

django

I'm using the render_to_response shortcut and don't want to craft a specific Response object to add additional headers to prevent client-side caching.

I'd like to have a response that contains:

  • Pragma: no-cache
  • Cache-control : no-cache
  • Cache-control: must-revalidate

And all the other nifty ways that browsers will hopefully interpret as directives to avoid caching.

Is there a no-cache middleware or something similar that can do the trick with minimal code intrusion?

like image 854
Lorenzo Avatar asked Jan 19 '10 17:01

Lorenzo


People also ask

What are the caching strategies in Django?

To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.

Does Django automatically cache?

Django stated in their docs that all query sets are automatically cached, https://docs.djangoproject.com/en/dev/topics/db/queries/#caching-and-querysets.

What mechanism is used to enable caching for an individual view in Django?

Using Memcached One of the most popular and efficient types of cache supported natively by Django is MEMCACHED .

Which view decorator module can be used to control server and client side caching?

Conditional view processingdecorators. http can be used to control caching behavior on particular views. These decorators can be used to generate ETag and Last-Modified headers; see conditional view processing.


2 Answers

You can achieve this using the cache_control decorator. Example from the documentation:

from django.views.decorators.cache import never_cache  @never_cache def myview(request):    # ... 
like image 163
Kristian Avatar answered Sep 23 '22 04:09

Kristian


This approach (slight modification of L. De Leo's solution) with a custom middleware has worked well for me as a site wide solution:

from django.utils.cache import add_never_cache_headers  class DisableClientSideCachingMiddleware(object):     def process_response(self, request, response):         add_never_cache_headers(response)         return response 

This makes use of add_never_cache_headers.


If you want to combine this with UpdateCacheMiddleware and FetchFromCacheMiddleware, to enable server-side caching while disabling client-side caching, you need to add DisableClientSideCachingMiddleware before everything else, like this:

MIDDLEWARE_CLASSES = (     'custom.middleware.DisableClientSideCachingMiddleware',     'django.middleware.cache.UpdateCacheMiddleware',     # ... all other middleware ...     'django.middleware.cache.FetchFromCacheMiddleware', ) 
like image 42
Meilo Avatar answered Sep 26 '22 04:09

Meilo