Refactor Crazy Egg module into its own app

Also removed the console service.  This commit has not been tested.
This commit is contained in:
Joost Cassee 2011-01-27 00:33:35 +01:00
parent 05c82b833a
commit 9a7d557036
7 changed files with 182 additions and 100 deletions

View file

@ -0,0 +1,127 @@
"""
==================================
Crazy Egg -- visual click tracking
==================================
`Crazy Egg`_ is an easy to use hosted web application that visualizes
website clicks using heatmaps. It allows you to discover the areas of
web pages that are most important to your visitors.
.. _`Crazy Egg`: http://www.crazyegg.com/
.. crazy-egg-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:`crazy-egg-configuration`.
In order to use the template tag, you need to add
:mod:`analytical.crazy_egg` to the installed applications list in the
project :file:`settings.py` file::
INSTALLED_APPS = [
...
'analytical.crazy_egg',
...
]
The Crazy Egg tracking code is inserted into templates using a template
tag. Load the :mod:`crazy_egg` template tag library and insert the
:ttag:`crazy_egg` 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 bottom of the HTML body::
{% load crazy_egg %}
...
{% crazy_egg %}
</body>
</html>
.. _crazy-egg-configuration:
Configuration
=============
Before you can use the Crazy Egg integration, you must first set your
account number. You can also segment the click analysis through user
variables.
.. _crazy-egg-account-number:
Setting the account number
--------------------------
Crazy Egg gives you a unique account number, and the :ttag:`crazy egg`
tag will include it in the rendered Javascript code. You can find your
account number by clicking the link named "What's my code?" in the
dashboard of your Crazy Egg account. Set
:const:`CRAZY_EGG_ACCOUNT_NUMBER` in the project :file:`settings.py`
file::
CRAZY_EGG_ACCOUNT_NUMBER = 'XXXXXXXX'
If you do not set an account number, the tracking code will not be
rendered.
.. _crazy-egg-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.
.. _crazy-egg-uservars:
User variables
--------------
Crazy Egg can segment clicks based on `user variables`_. If you want to
set a user variable, use the context variables ``crazy_egg_var1``
through ``crazy_egg_var5`` when you render your template::
context = RequestContext({'crazy_egg_var1': 'red',
'crazy_egg_var2': 'male'})
return some_template.render(context)
If you use the same user variables in different views and its value can
be computed from the HTTP request, you can also set them in a context
processor that you add to the :data:`TEMPLATE_CONTEXT_PROCESSORS` list
in :file:`settings.py`::
def segment_on_ip_proto(request):
addr = request.META.get('HTTP_X_FORWARDED_FOR',
request.META.get('REMOTE_ADDR', ''))
proto = 'ipv6' if ':' in addr else 'ipv4'
return {'crazy_egg_var3': proto}
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.
.. _`user variables`: https://www.crazyegg.com/help/Setting_Up_A_Page_to_Track/How_do_I_set_the_values_of_User_Var_1_User_Var_2_etc_in_the_confetti_and_overlay_views/
----
Thanks go to Crazy Egg for their support with the development of this
application.
"""
crazy_egg_service = {
'body_bottom': 'analytical.crazy_egg.templatetags.crazy_egg.CrazyEggNode',
}

View file

@ -0,0 +1,52 @@
"""
Crazy Egg template tags.
"""
import re
from django.template import Library, Node, TemplateSyntaxError
from analytical.utils import is_internal_ip, disable_html
ACCOUNT_NUMBER_RE = re.compile(r'^\d{8}$')
SETUP_CODE = """<script type="text/javascript" src="//dnn506yrbagrg.cloudfront.net/pages/scripts/%(account_nr_1)s/%(account_nr_2)s.js"</script>"""
USERVAR_CODE = "CE2.set(%(varnr)d, '%(value)s');"
register = Library()
@register.tag
def crazy_egg(parser, token):
"""
Crazy Egg tracking template tag.
Renders Javascript code to track page clicks. You must supply
your Crazy Egg account number (as a string) in the
``CRAZY_EGG_ACCOUNT_NUMBER`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no arguments" % bits[0])
return CrazyEggNode()
class CrazyEggNode(Node):
def __init__(self):
self.account_nr = self.get_required_setting('CRAZY_EGG_ACCOUNT_NUMBER',
ACCOUNT_NUMBER_RE,
"must be a string containing an eight-digit number")
def render(self, context):
html = SETUP_CODE % {'account_nr_1': self.account_nr[:4],
'account_nr_2': self.account_nr[4:]}
values = (context.get('crazy_egg_var%d' % i) for i in range(1, 6))
vars = [(i, v) for i, v in enumerate(values, 1) if v is not None]
if vars:
js = " ".join(USERVAR_CODE % {'varnr': varnr, 'value': value}
for (varnr, value) in vars)
html = '%s\n<script type="text/javascript">%s</script>' \
% (html, js)
if is_internal_ip(context):
html = disable_html(html, 'Crazy Egg')
return html

View file

@ -1,42 +0,0 @@
"""
Console debugging service.
"""
from analytical.services.base import AnalyticalService
DEBUG_CODE = """
<script type="text/javascript">
if(typeof(console) !== 'undefined' && console != null) {
%s
}
</script>
"""
LOG_CODE_ANONYMOUS = """
console.log('Analytical: rendering analytical_%(location)s tag');
"""
LOG_CODE_IDENTIFIED = """
console.log('Analytical: rendering analytical_%(location)s tag for user %(identity)s');
"""
class ConsoleService(AnalyticalService):
def render_head_top(self, context):
return self._render_code('head_top', context)
def render_head_bottom(self, context):
return self._render_code('head_bottom', context)
def render_body_top(self, context):
return self._render_code('body_top', context)
def render_body_bottom(self, context):
return self._render_code('body_bottom', context)
def _render_code(self, location, context):
vars = {'location': location, 'identity': self.get_identity(context)}
if vars['identity'] is None:
debug_code = DEBUG_CODE % LOG_CODE_ANONYMOUS
else:
debug_code = DEBUG_CODE % LOG_CODE_IDENTIFIED
return debug_code % vars

View file

@ -1,31 +0,0 @@
"""
Crazy Egg service.
"""
import re
from analytical.services.base import AnalyticalService
ACCOUNT_NUMBER_RE = re.compile(r'^\d{8}$')
SETUP_CODE = """<script type="text/javascript" src="//dnn506yrbagrg.cloudfront.net/pages/scripts/%(account_nr_1)s/%(account_nr_2)s.js"</script>"""
USERVAR_CODE = "CE2.set(%(varnr)d, '%(value)s');"
USERVAR_CONTEXT_VAR = 'crazy_egg_uservars'
class CrazyEggService(AnalyticalService):
def __init__(self):
self.account_nr = self.get_required_setting('CRAZY_EGG_ACCOUNT_NUMBER',
ACCOUNT_NUMBER_RE,
"must be a string containing an eight-digit number")
def render_body_bottom(self, context):
html = SETUP_CODE % {'account_nr_1': self.account_nr[:4],
'account_nr_2': self.account_nr[4:]}
uservars = context.get(USERVAR_CONTEXT_VAR, {})
if uservars:
js = "".join(USERVAR_CODE % {'varnr': varnr, 'value': value}
for (varnr, value) in uservars.items())
html = '%s\n<script type="text/javascript">%s</script>' \
% (html, js)
return html

View file

@ -14,7 +14,7 @@ from django.utils.importlib import import_module
DEFAULT_SERVICES = [
'analytical.chartbeat.chartbeat_service',
'analytical.clicky.clicky_service',
'analytical.crazy_egg.CrazyEggService',
'analytical.crazy_egg.crazy_egg_service',
'analytical.google_analytics.GoogleAnalyticsService',
'analytical.kiss_insights.KissInsightsService',
'analytical.kiss_metrics.KissMetricsService',

View file

@ -1,27 +1,3 @@
Crazy Egg -- visual click tracking
==================================
.. currentmodule:: analytical.crazy_egg
`Crazy Egg`_ is an easy to use hosted web application that visualizes
website clicks using heatmaps. It allows you to discover the areas of
web pages that are most important to your visitors.
.. _`Crazy Egg`: http://www.crazyegg.com/
Required settings
-----------------
.. data:: CRAZY_EGG_ACCOUNT_NUMBER
Your Crazy Egg account number::
CRAZY_EGG_ACCOUNT_NUMBER = '12345678'
You can find the account number by clicking the link named "What's my
code?" in the dashboard of your Crazy Egg account.
----
Thanks go to Crazy Egg for their support with the development of this
application.
.. automodule:: analytical.crazy_egg