Strip Google Analytics cookies for caching middleware purposes

1
2
3
4
5
6
7
8
9
import re

class StripCookieMiddleware(object):
    strip_re = re.compile(r'(__utm.=.+?(?:; |$))')
    def process_request(self, request):
        try:
            cookie = self.strip_re.sub('', request.META['HTTP_COOKIE'])
            request.META['HTTP_COOKIE'] = cookie
        except: pass

More like this

  1. Google Analytics Template Tag by blinks 5 years, 7 months ago
  2. Cookieless Session Middleware by juliocarlos 4 years, 6 months ago
  3. Another Cookieless Session Middleware by lvscar 4 years ago
  4. CurrentSessionIDMiddleware by troolee 2 years, 11 months ago
  5. Google Authentification by marcossousa 3 years, 4 months ago

Comments

smulloni (on October 25, 2009):

Google ads introduces cookies with a similar effect, and also use a double-underscore prefix. So I'll trying this regex to deal with both:

strip_re = re.compile(r'\b(__[^=]+=.+?(?:; |$))')

Also, this will reserve the double underscore namespace for any cookies I may want to plant that shouldn't affect server-side caching.

#

nf (on October 26, 2009):

Good idea, smulloni!

I've just updated the code to wrap the replacement in a try/except, as if the user had no cookies when visiting the site it would raise a KeyError. Not good!

#

andybak (on October 26, 2009):

How does this relate to #6552 and #9249? I haven't looked into the caching internals in any depth and I naively assumed it was a 'switch on and forget' type of thing.

Does #6552 fix this? If not - does this snippet interfere with the workings of Google Analytics?

#

smulloni (on October 26, 2009):

The patch for Django bug #6552 doesn't fix this.

This snippet should have no effect on google analytics. It doesn't prevent the client from having the cookie or reporting it to google; it does cause Django itself to ignore the cookie. If you want to access google analytics cookies from within django, for some reason, this would make it impossible. But I doubt that you do.

#

Romain Hardouin (on October 28, 2009):

nice

#

italomaia (on January 11, 2011):

This snippet worked really nice. Thanks!

#

sk1p (on July 6, 2011):

Please be aware that using

strip_re = re.compile(r'\b(__[^=]+=.+?(?:; |$))')

as proposed in the first comment, will cause problems with the messaging framework (django.contrib.messages) in current django versions, as it uses __json_message for storing messages in cookies.

#

(Forgotten your password?)