Refactor KISSmetrics module into its own app

This commit has not been tested.
This commit is contained in:
Joost Cassee 2011-01-27 17:53:32 +01:00
parent 774970ec46
commit e0190a9cb0
8 changed files with 197 additions and 125 deletions

View file

@ -81,13 +81,13 @@ will not be rendered.
Identifying authenticated users
-------------------------------
If your can identify website visitors, you can pass this information
on to KISSinsights so that you can tie survey submissions to customers.
If your websites identifies visitors, you can pass this information on
to KISSinsights so that you can tie survey submissions to customers.
By default, the username of an authenticated user is passed to
KISSinsights automatically. See :data:`ANALYTICAL_AUTO_IDENTIFY` for
important information about detecting authenticated visitors.
You can also send the identity yourself by adding the
You can also send the visitor identity yourself by adding the
``analytical_identity`` variable to the template context::
context = RequestContext({'analytical_identity': identity})

View file

@ -0,0 +1,117 @@
"""
==============================
KISSmetrics -- funnel analysis
==============================
KISSmetrics_ is an easy to implement analytics solution that provides a
powerful visual representation of your customer lifecycle. Discover how
many visitors go from your landing page to pricing to sign up, and how
many drop out at each stage.
.. _KISSmetrics: http://www.kissmetrics.com/
.. kiss-metrics-installation:
Installation
============
You only need to do perform these steps if you are not using the
generic :ttag:`analytical.*` tags. If you are, skip to
:ref:`kiss-metrics-configuration`.
In order to use the template tag, you need to add
:mod:`analytical.kiss_metrics` to the installed applications list in
the project :file:`settings.py` file::
INSTALLED_APPS = [
...
'analytical.kiss_metrics',
...
]
The KISSmetrics Javascript code is inserted into templates using a
template tag. Load the :mod:`kiss_metrics` template tag library and
insert the :ttag:`kiss_metrics` tag. Because every page that you want
to track must have the tag, it is useful to add it to your base
template. Insert the tag at the top of the HTML head::
{% load kiss_metrics %}
<html>
<head>
{% kiss_metrics %}
...
.. _kiss-metrics-configuration:
Configuration
=============
Before you can use the KISSmetrics integration, you must first set your
API key.
.. _kiss-metrics-api-key:
Setting the API key
-------------------
Every website you track events for with KISSmetrics gets its own API
key, and the :ttag:`kiss_metrics` tag will include it in the rendered
Javascript code. You can find the website API key by visiting the
website *Product center* on your KISSmetrics dashboard. Set
:const:`KISS_METRICS_API_KEY` in the project :file:`settings.py` file::
KISS_METRICS_API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
If you do not set an API key, the tracking code will not be rendered.
.. _kiss-metrics-internal-ips:
Internal IP addresses
---------------------
Usually you do not want to track clicks from your development or
internal IP addresses. By default, if the tags detect that the client
comes from any address in the :const:`INTERNAL_IPS` setting, the
tracking code is commented out. See :const:`ANALYTICAL_INTERNAL_IPS`
for important information about detecting the visitor IP address.
.. _kiss-metrics-identify-user:
Identifying users
-----------------
If your websites identifies visitors, you can pass this information on
to KISSmetrics so that you can tie events to users. By default, the
username of an authenticated user is passed to KISSmetrics
automatically. See :data:`ANALYTICAL_AUTO_IDENTIFY` for important
information about detecting authenticated visitors.
You can also send the visitor identity yourself by adding the
``analytical_identity`` variable to the template context::
context = RequestContext({'analytical_identity': identity})
return some_template.render(context)
If you can derive the identity from the HTTP request, you can also use
a context processor that you add to the
:data:`TEMPLATE_CONTEXT_PROCESSORS` list in :file:`settings.py`::
def identify(request):
try:
return {'analytical_identity': request.user.email}
except AttributeError:
return {}
Just remember that if you set the same context variable in the
:class:`~django.template.context.RequestContext` constructor and in a
context processor, the latter clobbers the former.
"""
kiss_metrics_service = {
'head_top': 'analytical.kiss_metrics.templatetags.kiss_metrics.KissMetricsNode',
}

View file

@ -0,0 +1,74 @@
"""
KISSmetrics template tags.
"""
import re
from django.template import Library, Node, TemplateSyntaxError
from django.utils import simplejson
from analytical.utils import is_internal_ip, disable_html
API_KEY_RE = re.compile(r'^[0-9a-f]{40}$')
TRACKING_CODE = """
<script type="text/javascript">
var _kmq = _kmq || [];
%(commands)s
function _kms(u){
setTimeout(function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = u;
var f = document.getElementsByTagName('script')[0];
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//i.kissmetrics.com/i.js');
_kms('//doug1izaerwt3.cloudfront.net/%(api_key)s.1.js');
</script>
"""
IDENTIFY_CODE = "_kmq.push(['identify', '%s']);"
EVENT_CODE = "_kmq.push(['record', '%(name)s', %(properties)s]);"
EVENT_CONTEXT_KEY = 'kiss_metrics_event'
register = Library()
@register.tag
def kiss_metrics(parser, token):
"""
KISSinsights tracking template tag.
Renders Javascript code to track page visits. You must supply
your KISSmetrics API key in the ``KISS_METRICS_API_KEY``
setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments" % bits[0])
return KissMetricsNode()
class KissMetricsNode(Node):
def __init__(self):
self.api_key = self.get_required_setting('KISS_METRICS_API_KEY',
API_KEY_RE,
"must be a string containing a 40-digit hexadecimal number")
def render(self, context):
commands = []
identity = self.get_identity(context)
if identity is not None:
commands.append(IDENTIFY_CODE % identity)
try:
name, properties = context[EVENT_CONTEXT_KEY]
commands.append(EVENT_CODE % {'name': name,
'properties': simplejson.dumps(properties)})
except KeyError:
pass
html = TRACKING_CODE % {'api_key': self.api_key,
'commands': " ".join(commands)}
if is_internal_ip(context):
html = disable_html(html, 'Mixpanel')
return html

View file

@ -1,51 +0,0 @@
"""
KISSmetrics service.
"""
import re
from django.utils import simplejson
from analytical.services.base import AnalyticalService
API_KEY_RE = re.compile(r'^[0-9a-f]{40}$')
SETUP_CODE = """
<script type="text/javascript">
var _kmq = _kmq || [];
%(commands)s
function _kms(u){
setTimeout(function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = u;
var f = document.getElementsByTagName('script')[0];
f.parentNode.insertBefore(s, f);
}, 1);
}
_kms('//i.kissmetrics.com/i.js');
_kms('//doug1izaerwt3.cloudfront.net/%(api_key)s.1.js');
</script>
"""
IDENTIFY_CODE = "_kmq.push(['identify', '%s']);"
JS_EVENT_CODE = "_kmq.push(['record', '%(name)s', %(properties)s]);"
class KissMetricsService(AnalyticalService):
def __init__(self):
self.api_key = self.get_required_setting('KISS_METRICS_API_KEY',
API_KEY_RE,
"must be a string containing a 40-digit hexadecimal number")
def render_head_top(self, context):
commands = []
identity = self.get_identity(context)
if identity is not None:
commands.append(IDENTIFY_CODE % identity)
return SETUP_CODE % {'api_key': self.api_key,
'commands': commands}
def render_event(self, name, properties):
return JS_EVENT_CODE % {'name': name,
'properties': simplejson.dumps(properties)}

View file

@ -1,45 +0,0 @@
"""
Mixpanel service.
"""
import re
from django.utils import simplejson
from analytical.services.base import AnalyticalService
MIXPANEL_TOKEN_RE = re.compile(r'^[0-9a-f]{32}$')
SETUP_CODE = """
<script type="text/javascript">
var mpq = [];
mpq.push(['init', '%(token)s']);
%(commands)s
(function() {
var mp = document.createElement("script"); mp.type = "text/javascript"; mp.async = true;
mp.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + "//api.mixpanel.com/site_media/js/api/mixpanel.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(mp, s);
})();
</script>
"""
IDENTIFY_CODE = "mpq.push(['identify', '%s']);"
EVENT_CODE = "mpq.push(['track', '%(name)s', %(properties)s]);"
class MixpanelService(AnalyticalService):
def __init__(self):
self.token = self.get_required_setting('MIXPANEL_TOKEN',
MIXPANEL_TOKEN_RE,
"must be a string containing a 32-digit hexadecimal number")
def render_head_bottom(self, context):
commands = []
identity = self.get_identity(context)
if identity is not None:
commands.append(IDENTIFY_CODE % identity)
return SETUP_CODE % {'token': self.token,
'commands': " ".join(commands)}
def render_event(self, name, properties):
return EVENT_CODE % {'name': name,
'properties': simplejson.dumps(properties)}

View file

@ -18,7 +18,7 @@ DEFAULT_SERVICES = [
'analytical.google_analytics.google_analytics_service',
'analytical.hubspot.hubspot_service',
'analytical.kiss_insights.kiss_insights_service',
'analytical.kiss_metrics.KissMetricsService',
'analytical.kiss_metrics.kiss_metrics_service',
'analytical.mixpanel.MixpanelService',
'analytical.optimizely.OptimizelyService',
]

View file

@ -1,26 +1,3 @@
KISSmetrics -- funnel analysis
==============================
.. currentmodule:: analytical.kiss_metrics
KISSmetrics_ is an easy to implement analytics solution that provides a
powerful visual representation of your customer lifecycle. Discover how
many visitors go from your landing page to pricing to sign up, and how
many drop out at each stage.
.. _KISSmetrics: http://www.kissmetrics.com/
The code is added to the top of the HTML head. By default, the
username of a logged-in user is passed to KISSmetrics. See
:data:`ANALYTICAL_AUTO_IDENTIFY`.
Required settings
-----------------
.. data:: KISSMETRICS_API_KEY
The website API key::
KISSMETRICS_API_KEY = '1234567890abcdef1234567890abcdef12345678'
You can find the website API key by visiting the website `Product
center` on your KISSmetrics dashboard.
.. automodule:: analytical.kiss_metrics