From 8c5ed948187a7142207cbaaf7d56d7bb5fe631ff Mon Sep 17 00:00:00 2001 From: Johann Schmitz Date: Wed, 4 May 2016 06:20:42 +0200 Subject: [PATCH] Exclude requests to admin site when tracking via PiwikTrackingMiddleware by default --- README.md | 2 ++ src/django_pypiwik/middleware.py | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/README.md b/README.md index 7bf41e2..ffea65f 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ If you have only one site, or all of your sites sending requests to the same piw `django-pypiwik` installs the `Piwik configuration` model. Use this model to connect your Django site with an Piwik site. +When using the `PiwikTrackingMiddleware`, the `PIWIK_TRACKING_MIDDLEWARE_EXCLUDE_ADMIN` option controls whether requests in the Django admin site should be tracked or not. # Usage @@ -79,6 +80,7 @@ You can also use the `track_page_view` decorator in your `urls.py` to wrap third ## PiwikTrackingMiddleware (since 0.1.6) You can also use the `PiwikTrackingMiddleware` to track page views by including `django_pypiwik.middleware.PiwikTrackingMiddleware` in your `MIDDLEWARE_CLASSES`. The middleware sends a server-to-server tracking call in the `process_response` hook. +The `PIWIK_TRACKING_MIDDLEWARE_PARAMS` option (a dict) in your settings.py let you control other tracking parameters to send to Piwik. Please note that the call is synchronous - if your tracking server is slow to response, the response time of your application will suffer. diff --git a/src/django_pypiwik/middleware.py b/src/django_pypiwik/middleware.py index c6b2103..c011d63 100644 --- a/src/django_pypiwik/middleware.py +++ b/src/django_pypiwik/middleware.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from django.conf import settings +from django.core.urlresolvers import reverse, NoReverseMatch from django_pypiwik.tracker import DjangoPiwikTracker @@ -7,6 +8,16 @@ from django_pypiwik.tracker import DjangoPiwikTracker class PiwikTrackingMiddleware(object): def process_response(self, request, response): + exclude_admin = getattr(settings, 'PIWIK_TRACKING_MIDDLEWARE_EXCLUDE_ADMIN', True) == True + + try: + admin_url = reverse('admin:index') + except NoReverseMatch: + admin_url = None + + if exclude_admin and admin_url and request.path.startswith(admin_url): + return response + tracker = DjangoPiwikTracker.for_current_site(request=request) tracker.track_page_view(**getattr(settings, 'PIWIK_TRACKING_MIDDLEWARE_PARAMS', {})) return response