Commits

Mikhail Korobov committed e13a973

Initial import

Comments (0)

Files changed (10)

+syntax: glob
+
+#IDE files
+.settings/*
+.project
+.pydevproject
+.cache/*
+
+#temp files
+*.pyc
+*.pyo
+*.orig
+*~
+
+#misc files
+pip-log.txt
+
+#os files
+.DS_Store
+Thumbs.db
+
+#setup files
+build/
+dist/
+.build/
+MANIFEST
+Copyright (c) 2010 Mikhail Korobov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+include *.txt
+include *.rst
+recursive-include docs *.txt
+recursive-include chart_tools *.html
+==================
+django-chart-tools
+==================
+
+django-chart-tools is a simple app for creating charts in django templates
+using Google Chart API. It doesn't try to invent another language for defining
+charts unlike other Google Chart API wrappers. It instead make it easy to
+leverage the power of existing user-friendly chart-building tools like
+http://imagecharteditor.appspot.com/ or http://dexautomation.com/googlechartgenerator.php
+
+Installation
+============
+
+::
+
+    $ pip install django-chart-tools
+
+or ::
+
+    $ easy_install django-chart-tools
+
+or grab the latest and the greatest version from bitbucket
+(http://bitbucket.org/kmike/django-chart-tools)
+
+Then add 'chart_tools' to your INSTALLED_APPS.
+
+Usage
+=====
+
+1. Generate a chart you like using http://imagecharteditor.appspot.com/ .
+
+2. Copy&paste output to your template and wrap it with
+   {% chart %} ... {% endchart %} tags::
+
+        {% load chart_tags %}
+        {% chart %}
+            http://chart.apis.google.com/chart
+               ?chxr=0,0,160
+               &chxt=y
+               &chbh=a
+               &chs=440x220
+               &cht=bvs
+               &chco=4D89F9
+               &chds=0,160
+               &chd=t:10,50,60,80,40,60,30
+               &chtt=Horizontal+bar+chart
+        {% endchart %}
+
+    You'll get the <img/> tag with generated chart in you template after rendering.
+
+3. chart tag also allows cleaned-up version of the example above::
+
+       {% load chart_tags %}
+       {% chart %}
+            chxr=0,0,160
+            chxt=y
+            chbh=a
+            chs=440x220
+            cht=bvs
+            chco=4D89F9
+            chds=0,160
+            chd=t:10,50,60,80,40,60,30
+            chtt=Horizontal+bar+chart
+       {% endchart %}
+
+4. Replace test data with your real data. For example, we want to provide
+   real values. Change the test data in Image Chart Editor. The
+   parameter we change will be highlited. It is 'chd' in our case. So now
+   we replace 'chd' data with real data that comes from view::
+
+      {% load chart_tags %}
+      {% chart %}
+           chxr=0,0,160
+           chxt=y
+           chbh=a
+           chs=440x220
+           cht=bvs
+           chco=4D89F9
+           chds=0,160
+           chd=t:{{ values|join:',' }}
+           chtt=Horizontal+bar+chart
+      {% endchart %}
+
+That's all.
+
+There is also up-to-date API reference from Google:
+http://code.google.com/intl/en/apis/chart/docs/chart_params.html
+
+What is {% chart %} tag for
+===========================
+
+I found plain copy-pasted <img> html tag with some {{ variables }}
+unmaintainable and unreadable so the {% chart %} was introduced.
+
+1. It removes all whitespaces;
+2. builds chart url from parameter list;
+3. generates the <img> tag with proper 'src', 'width' and 'height' attributes
+
+so generated charts can be nicely formatted and it is possible to maintain
+them later.
+
+
+Reusable chart tags
+===================
+
+Once you created a chart you like you'll possibly want to use it multiple
+times. The preferred way is to write inclusion template tag around your
+template::
+
+    from django import template
+    register = template.Library()
+
+    @register.inclusion_tag('chart_tools/bar_chart.html')
+    def bar_chart(values, captions, size='580x100', max_value=None):
+        max_value = max_value or max(values)
+        return {
+            'values': values,
+            'captions': captions,
+            'size': size,
+            'max_value': max_value,
+        }
+
+This example bar_chart tag is included in django-chart-tools.

chart_tools/__init__.py

Empty file added.

chart_tools/models.py

+#

chart_tools/templates/chart_tools/bar_chart.html

+{% load chart_tools %}
+{% chart %}
+    cht=bvs
+    chco=4D89F9
+    chd=t:{{ values|join:"," }}
+    chs={{ size }}
+    chds=0,{{ max_value }}
+    chxr=1,0,{{ max_value }}
+    chbh=a
+    chxt=x,y
+    chxl=0:|{{ captions|join:"|" }}
+{% endchart %}

chart_tools/templatetags/__init__.py

Empty file added.

chart_tools/templatetags/chart_tags.py

+#coding: utf-8
+import re
+from django import template
+from django.template import TemplateSyntaxError
+register = template.Library()
+
+API_URL = 'http://chart.apis.google.com/chart'
+
+@register.inclusion_tag('chart_tools/bar_chart.html')
+def bar_chart(values, captions, size='580x100', max_value=None):
+    max_value = max_value or max(values)
+    return {
+        'values': values,
+        'captions': captions,
+        'size': size,
+        'max_value': max_value,
+    }
+
+@register.tag
+def chart(parser, token):
+    params = token.split_contents()
+    if len(params) == 2:
+        attr = params[1]
+    elif len(params) == 1:
+        attr = ''
+    else:
+        raise TemplateSyntaxError('Invalid arguments')
+    nodelist = parser.parse(('endchart',))
+    parser.delete_first_token()
+    return ChartNode(nodelist, attr)
+
+class ChartNode(template.Node):
+    def __init__(self, nodelist, attr):
+        self.nodelist = nodelist
+        self.attr = attr
+
+    def render(self, context):
+        input = self.nodelist.render(context)
+        return _prepare_chart(input, self.attr)
+
+def _prepare_chart(input, attr):
+    # remove whitespaces
+    input_lines = input.replace(' ', '').splitlines()
+
+    # build url
+    lines = []
+    for line in filter(None, input_lines):
+        if not line.endswith('&'):
+            line = line + '&'
+        lines.append(line)
+
+    if not lines[0].startswith('?'):
+        lines[0] = '?'+lines[0]
+    lines[-1] = lines[-1].rstrip('&')
+
+    output = ''.join(lines)
+
+    # get the width and height from chart data for later use
+    width = height = ''
+    size = re.search("chs=(\d+)x(\d+)", output)
+    if size:
+        width = size.group(1)
+        height = size.group(2)
+
+    # prepend with API_URL
+    if not output.startswith(API_URL):
+        output = API_URL + output
+
+    img = "<img src='%s' width='%s' height='%s' alt='' %s />" % (output, width, height, attr)
+    return img
+#!/usr/bin/env python
+from distutils.core import setup
+
+version='0.1.0'
+
+setup(
+    name='django-chart-tools',
+    version=version,
+    author='Mikhail Korobov',
+    author_email='kmike84@gmail.com',
+
+    packages=['chart_tools', 'chart_tools.templatetags'],
+    package_data = {'chart_tools': ['templates/chart_tools/*.html']},
+
+    url='http://bitbucket.org/kmike/django-chart-tools/',
+    download_url = 'http://bitbucket.org/kmike/django-chart-tools/get/tip.zip',
+    license = 'MIT license',
+    description = """A thin wrapper around Google Chart API that tries not to invent a new language for describing charts.""",
+
+    long_description = open('README.rst').read(),
+
+    classifiers=(
+        'Development Status :: 3 - Alpha',
+        'Environment :: Web Environment',
+        'Framework :: Django',
+        'Intended Audience :: Developers',
+        'License :: OSI Approved :: MIT License',
+        'Programming Language :: Python',
+        'Topic :: Software Development :: Libraries :: Python Modules',
+    ),
+)