piwik release 1.0
[auf_django_piwik.git] / auf / django / piwik / middleware.py
1 # -*- coding: utf-8 -*-
2
3 import re
4 from settings import PIWIK_TOKEN, PIWIK_HOST, PIWIK_TRACKCODE
5
6 ire_body = re.compile(re.escape('</body>'), re.IGNORECASE)
7
8
9 class TrackMiddleware:
10
11 def process_response(self, request, response):
12 """
13 Trackcode injection avant le body s'il y a un token piwik dans la conf
14 locale.
15 """
16 if PIWIK_TOKEN is None:
17 return response
18
19 if request.is_secure():
20 protocol = "https"
21 else:
22 protocol = "http"
23
24 track = PIWIK_TRACKCODE % {
25 'host': PIWIK_HOST,
26 'token': PIWIK_TOKEN,
27 'protocol': protocol,
28 }
29
30 content = response.content
31 content_with_trackcode = ire_body.sub('%s</body>' % track, content)
32 response.content = content_with_trackcode
33 return response