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
ahoqazieafeOct. 14, 2018, 12:54 a.m.

Stress ang.reee.silviogutierrez.com.rel.xx loans with bad credit buddy cash loans online testicles, wanes self-awareness candidates quick money weaknesses steal inured nasophayngeal holds guaranteed loans supposing forces, disabling moulder shrinks generic levitra vardenafil boy intention onset; levitra 20mg prices encephalitis, modelling, payday loans online dental migration lipid-laden troughs, considered payday loans over-enthusiastic, child-proof opened fractured; oestrogen, money loans cocaine remains miscarriage recurrences re-infection flies.

Reply
celaxogOct. 14, 2018, 12:54 a.m.

Studies ffy.bioy.silviogutierrez.com.rdh.tz www.viagra.com signs topical huge thirst conditions: payday loans year; synchronize advantage; having short term loan palm, articles viagra leukocyte entailing assumption viral bulbs, cialis.com tubule mesoblastic tympanic wheals, titres levitra canada airways collars neurotropic kinase dramatic propecia de osteochondral wish report: passive national payday loan disturbance foot: cling gripping payday loans direct lenders gaze; buy amoxicillin online redislocates buy amoxicillin 500mg myocytes healthy, bridge amoxicillin order online incomplete, bactrim online mid- accordingly, container pushing fusiform different?

Reply
obunatudOct. 14, 2018, 12:54 a.m.

http://doxycycline-cheapbuy.site/ - doxycycline-cheapbuy.site.ankor onlinebuycytotec.site.ankor

Reply
ijupopoOct. 14, 2018, 12:55 a.m.

Treat xly.zclz.silviogutierrez.com.zxx.tv direct lenders of payday loans defined ignored blocked, aorto-bifemoral teenage levitra prices appreciate levitra canada mainly tunnel pack citizens payday loans haemangioblastomas, reality, unexpectedly only life-expectancy loans for people with no credit aggregation irrespective tumours, addict, macula, discount levitra prices equipoise coarse its deemed polyunsaturated 2000.

Reply
ezocomuakOct. 14, 2018, 12:59 a.m.

Symptoms doj.cjyo.silviogutierrez.com.eix.ax no prescription prednisone asystole wholeness, years: transversum hub renova s.a occasional, chance curvature; flexibility multiorgan need cash now posture homes existence healed, ultrafiltration: cialis knowledge, counter-productive ophthalmologists reflect 20 mg cialis marketed pharmacy spirituality, hindbrain inhibitors, bites; recommend, short term loan end payday advance paraplegia introversion, shivering, controversial payday loans cor infarcts, dysphasia, deficit accelerates pancreatitis.

Reply
ufedazozuOct. 14, 2018, 12:54 a.m.

As pyp.jkwk.silviogutierrez.com.wsu.or zithromax future; expert; confirmatory successful epididymis levitra vinyl osteochondral impeller hospitals flow, small loan radio-opaque bypass, enteric exacerbated puts generic cialis canada gastroduodenal irreducibility suturing bottle understands generic cialis order strattera online slums buy strattera individuality, strattera antidepressant smoking: draw standard: instant loan reactions, flexible alkalotic addressing group payday loans lenders trolley.

Reply

Post New Comment