2 from django.contrib.sites.models import Site
3 from piwik.django.models import PiwikSite
4 from django.conf import settings
6 from functools import update_wrapper
10 from random import random
11 from inspect import isclass
13 logger = logging.getLogger(__name__)
17 url = settings.PIWIK_URL + u"/piwik.php?"
18 url += u'&'.join([k + u"=" + str(v) for k, v in kw.items()])
19 logger.info("piwik url: %s" % url)
25 def piwik_track(klass_or_method):
26 """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
27 Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
29 # Retrieve piwik information
30 current_site = Site.objects.get_current()
31 piwik_site = PiwikSite.objects.filter(site=current_site.id)
33 if len(piwik_site) == 0:
34 logger.debug("No PiwikSite is configured for Site " + current_site.name)
35 return klass_or_method
37 id_piwik = piwik_site[0].id_site
38 host = urlparse.urlsplit(settings.PIWIK_URL).netloc
41 if isclass(klass_or_method):
42 klass = klass_or_method
43 call_func = klass.__call__
45 call_func = klass_or_method
47 def wrap(self, request, *args, **kw):
48 conn = httplib.HTTPConnection(host)
49 conn.request('GET', piwik_url(
51 apiv=PIWIK_API_VERSION,
52 rand=int(random() * 0x10000),
53 token_auth=urllib.quote(settings.PIWIK_TOKEN),
54 cip=urllib.quote(request.META['REMOTE_ADDR']),
55 url=urllib.quote('http://' + request.META['HTTP_HOST'] + request.path),
56 urlref=urllib.quote(request.META['HTTP_REFERER']) if 'HTTP_REFERER' in request.META else '',
60 return call_func(self, request, *args, **kw)
63 update_wrapper(wrap, call_func)
65 if isclass(klass_or_method):