Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

* initial commit

  • Loading branch information...
commit 75534eb66c8ad8040296d599bd35da09ea8f66ca 0 parents
@idlesign authored
3  .gitignore
@@ -0,0 +1,3 @@
+*.pyc
+.project
+.pydevproject
27 LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2010, django-sitemetrics project
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ 3. Neither the name of the django-sitemetrics project nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 README.md
@@ -0,0 +1,44 @@
+SiteMetrics for Django
+=======================================
+http://github.com/idlesign/django-sitemetrics
+
+### What's that ###
+
+django-sitemetrics is a reusable application for Django 1.1+ that offers easy integration with different site metrics service providers.
+
+### Currently supported site metrics providers ###
+
+1. **Yandex Metrika** — http://metrika.yandex.ru/
+Provider alias: 'yandex'
+2. **Google Analytics** — http://www.google.com/analytics/
+Provider alias: 'google'
+
+
+### How to use ###
+
+1. Add the 'sitemetrics' application to 'INSTALLED_APPS' in your settings file (usually 'settings.py')
+2. Add '{% load sitemetrics %}' tag to the top of a template (usually base template, e.g. 'base.html')
+
+Then you have two options that add metrics client code to your page:
+
++ Use so-called 'four arguments' sitemetrics tag notation:
+**{% sitemetrics by google for "UA-000000-0" %}**
+Here: 'google' — provider alias; 'UA-000000-0' — keycode argument.
+That's how you put Google Analytics client code (with 'UA-000000-0' keycode) into page.
+
++ Use so-called 'no arguments' sitemetrics tag notation:
+**{% sitemetrics %}**
+That's how you put all client codes registered and active for the current site.
+Client codes are registered with sites through Django Admin site interface.
+*** 'Admin site' and 'Sites' from Django contrib are required for this option to work.**
+*** './manage.py syncdb' is required just once for this option to work (it installs sitemetrics table into database).**
+
+### How to add site metrics providers ###
+
+1. Edit 'sitemetrics/models.py'. Add new provider alias and name into KEYCODE_PROVIDERS list.
+2. Edit 'sitemetrics/templates/sitemetrics/sitemetrics.tpl'. Add another 'ifequal' clause with 'keycode.provider' check against the alias of your new provider.
+
+### Translating django-sitemetrics ###
+
+You can translate application into your language if it is supported by Django.
+For translation tips refer to Django documentation: http://docs.djangoproject.com/en/1.1/topics/i18n/localization/
28 setup.py
@@ -0,0 +1,28 @@
+import os
+from setuptools import setup, find_packages
+from sitemetrics import VERSION
+
+f = open(os.path.join(os.path.dirname(__file__), 'README'))
+readme = f.read()
+f.close()
+
+setup(
+ name='django-sitemetrics',
+ version=".".join(map(str, VERSION)),
+ description='This reusable Django app can help you to site metrics (Yandex Metrika, Google Analytics)',
+ long_description=readme,
+ author="Igor 'idle sign' Starikov",
+ author_email='idlesign@yandex.ru',
+ url='http://github.com/idlesign/django-sitemetrics',
+ packages=find_packages(),
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'Environment :: Web Environment',
+ 'Framework :: Django',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: BSD License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+
+ ],
+)
1  sitemetrics/__init__.py
@@ -0,0 +1 @@
+VERSION = (0, 1, 0)
11 sitemetrics/admin.py
@@ -0,0 +1,11 @@
+from sitemetrics.models import Keycode
+from django.contrib import admin
+
+class KeycodeAdmin(admin.ModelAdmin):
+ list_display = ('site', 'provider', 'keycode', 'active',)
+ list_editable = ('active',)
+ search_fields = ['keycode']
+ list_filter = ['site', 'provider', 'active']
+ ordering = ['site']
+
+admin.site.register(Keycode, KeycodeAdmin)
BIN  sitemetrics/locale/ru/LC_MESSAGES/django.mo
Binary file not shown
58 sitemetrics/locale/ru/LC_MESSAGES/django.po
@@ -0,0 +1,58 @@
+# SiteMetrics reusable Django application russian translation file.
+# Copyright (C) 2010, Igor Starikov aka idle sign
+# This file is distributed under the same license as the Django package.
+# idle sign <idlesign@yandex.ru>, 2010.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: SiteMetrics\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2010-05-12 11:49+0700\n"
+"PO-Revision-Date: 2010-05-12 11:50+0700\n"
+"Last-Translator: Igor 'idle sign' Starikov <idlesign@yandex.ru>\n"
+"Language-Team: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Poedit-Language: Russian\n"
+"X-Poedit-Country: RUSSIAN FEDERATION\n"
+"X-Poedit-SourceCharset: utf-8\n"
+
+#: models.py:6
+msgid "Site"
+msgstr "Сайт"
+
+#: models.py:6
+msgid "Site for which metrics keycode is registered."
+msgstr "Cайт, на который зарегистрирован ключ."
+
+#: models.py:7
+msgid "Provider"
+msgstr "Сервис"
+
+#: models.py:7
+msgid "Metrics service provider name."
+msgstr "Сервис, предоставляющий метрику."
+
+#: models.py:8
+#: models.py:11
+msgid "Keycode"
+msgstr "Ключ"
+
+#: models.py:8
+msgid "Keycode or identifier given by metrics service provider for site(s)."
+msgstr "Ключ (идентификатор) для сайта, выданный сервисом метрики."
+
+#: models.py:9
+msgid "Active"
+msgstr "Используется"
+
+#: models.py:9
+msgid "Whether this keycode is available to use."
+msgstr "Следует ли использовать ключ."
+
+#: models.py:12
+msgid "Keycodes"
+msgstr "Ключи"
+
19 sitemetrics/models.py
@@ -0,0 +1,19 @@
+from django.db import models
+from django.contrib.sites.models import Site
+from django.utils.translation import ugettext_lazy as _
+
+class Keycode(models.Model):
+ KEYCODE_PROVIDERS = (
+ ('yandex', 'Yandex Metrika'),
+ ('google', 'Google Analytics'),
+ )
+ site = models.ForeignKey(Site, verbose_name=_('Site'), help_text=_('Site for which metrics keycode is registered.'))
+ provider = models.CharField(_('Provider'), max_length=50, choices=KEYCODE_PROVIDERS, help_text=_('Metrics service provider name.'))
+ keycode = models.CharField(_('Keycode'), max_length=80, help_text=_('Keycode or identifier given by metrics service provider for site(s).'))
+ active = models.BooleanField(_('Active'), default=True, help_text=_('Whether this keycode is available to use.'))
+ class Meta:
+ verbose_name = _('Keycode')
+ verbose_name_plural = _('Keycodes')
+
+ def __unicode__(self):
+ return u'Keycode by %s for %s' % (self.provider, self.keycode)
11 sitemetrics/templates/sitemetrics/sitemetrics.tpl
@@ -0,0 +1,11 @@
+{% for keycode in keycodes %}
+ {% ifequal keycode.provider "yandex" %}
+ <script src="//mc.yandex.ru/metrika/watch.js" type="text/javascript"></script>
+ <div style="display:none;"><script type="text/javascript">try { var yaCounter{{ keycode.keycode }} = new Ya.Metrika({{ keycode.keycode }}); } catch(e){}</script></div>
+ <noscript><div style="position:absolute"><img src="//mc.yandex.ru/watch/{{ keycode.keycode }}" alt="" /></div></noscript>
+ {% endifequal %}
+ {% ifequal keycode.provider "google" %}
+ <script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));</script>
+ <script type="text/javascript">try{var pageTracker = _gat._getTracker("{{ keycode.keycode }}");pageTracker._trackPageview();} catch(err) {}</script>
+ {% endifequal %}
+{% endfor %}
0  sitemetrics/templatetags/__init__.py
No changes.
53 sitemetrics/templatetags/sitemetrics.py
@@ -0,0 +1,53 @@
+import urllib, hashlib
+from django import template
+from django.db import models
+from django.contrib.sites.models import Site
+
+register = template.Library()
+keycode = models.get_model('sitemetrics', 'Keycode')
+
+@register.tag
+def sitemetrics(parser, token):
+ """
+ Parses sitemetrics tag.
+
+ Two notation types are possible:
+ 1. No arguments:
+ {% sitemetrics %}
+ Used to render all metric counters registered and active for current site.
+ This requires 'Admin site' and 'Sites' from Django contrib.
+
+ 2. Four arguments:
+ {% sitemetrics by yandex for "138500" %}
+ Used to render custom metric counter with custom counter-id.
+ This is a simple template tag with no special requirements.
+
+ """
+ tokens = token.split_contents()
+ tokensNum = len(tokens)
+
+ if tokensNum == 1:
+ # Notation Type 1
+ currentSite = Site.objects.get_current()
+ keycodes = currentSite.keycode_set.filter(active=True)
+ elif tokensNum == 5:
+ # Notation Type 2
+ if tokens[1] == 'by' and tokens[3] == 'for':
+ keycodes = [{ 'provider':tokens[2], 'keycode':tokens[4][1:-1] },]
+ else:
+ raise template.TemplateSyntaxError, "A five argument notation of %r tag should look like {%% sitemetrics by yandex for \"138500\" %%}." % tokens[0]
+ else:
+ raise template.TemplateSyntaxError, "%r tag requires four or no arguments. E.g. {%% sitemetrics by yandex for \"138500\" %%} or {%% sitemetrics %%}." % tokens[0]
+
+ return sitemetricsNode(keycodes)
+
+class sitemetricsNode(template.Node):
+ """Renders specified site metric counter from template."""
+
+ def __init__(self, keycodes):
+ self.keycodes = keycodes
+ self.template = template.loader.get_template('sitemetrics/sitemetrics.tpl')
+
+ def render(self, context):
+ myContext = template.Context({'keycodes': self.keycodes,})
+ return self.template.render(myContext)
Please sign in to comment.
Something went wrong with that request. Please try again.