Fixing Site-Wide Caching in Django

Posted on Sept. 18, 2012

Caching in Django is elegant and simple, especially the site-wide cache for anonymous users. But if you use Google Analytics and other external cookies, it might not be working the way you intended. Read this tutorial to find out how to make your site as fast as it can be.

By enabling the site-wide cache in Django, you probably intended for pages every page to be cached for every anonymous users. That's the point, at least. The problem is, the page cache is set to Vary: Cookie. That means that if you have a session cookie or anything of the like, the cache will be different for each user.

Learning Django? Subscribe to my Django articles, tips and tutorials.

Fortunately, that's not a problem with Django itself, since anonymous users won't have cookies set. But it is a problem if you're using Google Analytics. That's because Google Analytics sets cookies that trigger the site-wide cache's Vary: Cookie condition. Luckily, fixing this is as easy as using a small piece of middleware and a touch of inheritance.

Let's create a new middleware file, call it middleware.py and place it in your project root. Add the following snippet to the file1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.middleware.cache import UpdateCacheMiddleware

import re


class SmartUpdateCacheMiddleware(UpdateCacheMiddleware):                        
    STRIP_RE = re.compile(r'\b(_[^=]+=.+?(?:; |$))')

    def process_request(self, request):                                         
        cookie = self.STRIP_RE.sub('', request.META.get('HTTP_COOKIE', ''))   
        request.META['HTTP_COOKIE'] = cookie

So what does this do? It replaces the middleware that comes with Django. Before passing on the cookies to the rest of the application, it strips out the cookies set by Google Analytics. That way, the Vary: Cookie condition won't be triggered, as your application won't see any of these cookies. To deploy these changes, simply find your middleware classes in settings.py, and replace django.middleware.cache.UpdateCacheMiddleware with middleware.SmartUpdateCacheMiddleware. Your middleware settings should look like so:

1
2
3
4
5
MIDDLEWARE_CLASSES = (                                                        
    'middleware.SmartUpdateCacheMiddleware',                                  
    # All your other middleware.                                              
     'django.middleware.cache.FetchFromCacheMiddleware',                      
)

And that's it. You're done.


  1. Many thanks to the people over at http://djangosnippets.org/snippets/1772/ for the middleware. 

Comments

django_devilNov. 3, 2017, 12:48 p.m.

please update the middleware.py file. It's not working...

Reply
silviogutierrezNov. 4, 2017, 5:43 p.m.

This was written for Django 1.2. I believe Django changed its middleware structure around Django 1.10, so I'm not sure when this stopped working. The concepts might still apply though.

Reply
Ben KaleskiMarch 20, 2019, 12:03 p.m.

Thanks for sharing these codes in your site and I will always get helped from your site. This website is also share in best papers writing service social media page because there mostly students are stuck in different codes.

Reply
dsdsdMay 6, 2019, 5:57 a.m.

Laisser les choses évoluer dans le bon sens. panerai montres La contingence exige du vendeur qu’il ait un esprit flexible et qu’il fasse les choses comme il se doit, mais pas trop, afin que les gens puissent être convaincus, laissant ainsi une bonne impression au client, transformant les inconvénients en avantages. Le boîtier de la patek philippe montres est en titane. La conception en matériau léger rend la montre plus dynamique. Le diamètre de 47 mm est idéal pour les hommes aux poignets épais, et le matériau léger ne fait pas le poignet. La table est trop lourde.

Reply
James HiltonJune 11, 2019, 9:58 a.m.

Çok destekleyici içerik, hakkında konuştuğunuz aynı problemle karşı karşıya kaldım Hoşgeldin Bonusu Veren Bahis Siteleri talimatlarınıza göre hareket ettikten sonra şimdi bu sorunun üstesinden geliyorum.

Reply
LinaJune 13, 2019, 5:44 a.m.

I am totally mad about racing but once i tried to race and i got injured. But i love to watch racing. Now i am fighting against whatsapp sniffer and making a group.

Reply
angilaJune 27, 2019, 12:26 p.m.

The music is the key to relax but not anytime when you got bad vibes everything seems bad to you-you don't want to get interact with anything because it makes you uncomfortable. can someone do my homework for me Its natural phenomena when you are worried about something so you don't like anything at all. Because your mind doesn't want to accept anything.

Reply
Sumitsingh72July 23, 2019, 12:07 p.m.
Reply
muneerAug. 5, 2019, 11:04 a.m.

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing Medical Emergency Help

Reply
MityaAug. 22, 2019, 9:36 a.m.

I have been working on wen designing and have designed may websites. Now i am working on a site on topic kannada whatsapp status video. It will be completed soon and will be available for my users soon.

Reply

Post New Comment