Skip to content

Improve support for writing Chart.js Javascript functions #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,48 @@ The URLs will render an image of a chart:

<img src="https://quickchart.io/chart?c=%7B%22type%22%3A+%22bar%22%2C+%22data%22%3A+%7B%22labels%22%3A+%5B%22Hello+world%22%2C+%22Test%22%5D%2C+%22datasets%22%3A+%5B%7B%22label%22%3A+%22Foo%22%2C+%22data%22%3A+%5B1%2C+2%5D%7D%5D%7D%7D&w=600&h=300&bkg=%23ffffff&devicePixelRatio=2.0&f=png" width="500" />

## Customizing your chart
# Using Javascript functions in your chart

Chart.js sometimes relies on Javascript functions (e.g. for formatting tick labels). There are a couple approaches:

- Build chart configuration as a string instead of a Python object. See `examples/simple_example_with_function.py`.
- Build chart configuration as a Python object and include a placeholder string for the Javascript function. Then, find and replace it.
- Use the provided `QuickChartFunction` class. See `examples/using_quickchartfunction.py` for a full example.

A short example using `QuickChartFunction`:
```py
qc = QuickChart()
qc.config = {
"type": "bar",
"data": {
"labels": ["A", "B"],
"datasets": [{
"label": "Foo",
"data": [1, 2]
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"callback": QuickChartFunction('(val) => val + "k"')
}
}],
"xAxes": [{
"ticks": {
"callback": QuickChartFunction('''function(val) {
return val + '???';
}''')
}
}]
}
}
}

print(qc.get_url())
```

# Customizing your chart

You can set the following properties:

Expand All @@ -75,6 +116,12 @@ The background color of the chart. Any valid HTML color works. Defaults to #ffff
### device_pixel_ratio: float
The device pixel ratio of the chart. This will multiply the number of pixels by the value. This is usually used for retina displays. Defaults to 1.0.

### host
Override the host of the chart render server. Defaults to quickchart.io.

### key
Set an API key that will be included with the request.

## Getting URLs

There are two ways to get a URL for your chart object.
Expand Down
40 changes: 40 additions & 0 deletions examples/using_quickchartfunction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from datetime import datetime

from quickchart import QuickChart, QuickChartFunction

qc = QuickChart()
qc.width = 600
qc.height = 300
qc.device_pixel_ratio = 2.0
qc.config = {
"type": "bar",
"data": {
"labels": [datetime(2020, 1, 15), datetime(2021, 1, 15)],
"datasets": [{
"label": "Foo",
"data": [1, 2]
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"callback": QuickChartFunction('(val) => val + "k"')
}
}, {
"ticks": {
"callback": QuickChartFunction('''function(val) {
return val + '???';
}''')
}
}],
"xAxes": [{
"ticks": {
"callback": QuickChartFunction('(val) => "$" + val')
}
}]
}
}
}

print(qc.get_url())
44 changes: 43 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "quickchart.io"
version = "0.1.5"
version = "0.2.0"
description = "A client for quickchart.io, a service that generates static chart images"
keywords = ["chart api", "chart image", "charts"]
authors = ["Ian Webster <ianw_pypi@ianww.com>"]
Expand All @@ -18,6 +18,7 @@ python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
requests = "^2.23.0"

[tool.poetry.dev-dependencies]
autopep8 = "^1.5.5"

[build-system]
requires = ["poetry>=0.12"]
Expand Down
53 changes: 44 additions & 9 deletions quickchart/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
"""A python client for quickchart.io, a web service that generates static
charts."""

import datetime
import json
import re
try:
from urllib import urlencode
except:
# For Python 3
from urllib.parse import urlencode

FUNCTION_DELIMITER_RE = re.compile('\"__BEGINFUNCTION__(.*?)__ENDFUNCTION__\"')


class QuickChartFunction:
def __init__(self, script):
self.script = script

def __repr__(self):
return self.script


def serialize(obj):
if isinstance(obj, QuickChartFunction):
return '__BEGINFUNCTION__' + obj.script + '__ENDFUNCTION__'
if isinstance(obj, (datetime.date, datetime.datetime)):
return obj.isoformat()
return obj.__dict__


def dump_json(obj):
ret = json.dumps(obj, default=serialize, separators=(',', ':'))
ret = FUNCTION_DELIMITER_RE.sub(
lambda match: json.loads('"' + match.group(1) + '"'), ret)
return ret


class QuickChart:
def __init__(self):
self.config = None
Expand All @@ -17,15 +45,21 @@ def __init__(self):
self.device_pixel_ratio = 1.0
self.format = 'png'
self.key = None
self.scheme = 'https'
self.host = 'quickchart.io'

def is_valid(self):
return self.config is not None

def get_url_base(self):
return '%s://%s' % (self.scheme, self.host)

def get_url(self):
if not self.is_valid():
raise RuntimeError('You must set the `config` attribute before generating a url')
raise RuntimeError(
'You must set the `config` attribute before generating a url')
params = {
'c': json.dumps(self.config) if type(self.config) == dict else self.config,
'c': dump_json(self.config) if type(self.config) == dict else self.config,
'w': self.width,
'h': self.height,
'bkg': self.background_color,
Expand All @@ -34,7 +68,7 @@ def get_url(self):
}
if self.key:
params['key'] = self.key
return 'https://quickchart.io/chart?%s' % urlencode(params)
return '%s/chart?%s' % (self.get_url_base(), urlencode(params))

def _post(self, url):
try:
Expand All @@ -43,7 +77,7 @@ def _post(self, url):
raise RuntimeError('Could not find `requests` dependency')

postdata = {
'chart': json.dumps(self.config) if type(self.config) == dict else self.config,
'chart': dump_json(self.config) if type(self.config) == dict else self.config,
'width': self.width,
'height': self.height,
'backgroundColor': self.background_color,
Expand All @@ -54,22 +88,23 @@ def _post(self, url):
postdata['key'] = self.key
resp = requests.post(url, json=postdata)
if resp.status_code != 200:
raise RuntimeError('Invalid response code from chart creation endpoint')
raise RuntimeError(
'Invalid response code from chart creation endpoint')
return resp

def get_short_url(self):
resp = self._post('https://quickchart.io/chart/create')
resp = self._post('%s/chart/create' % self.get_url_base())
parsed = json.loads(resp.text)
if not parsed['success']:
raise RuntimeError('Failure response status from chart creation endpoint')
raise RuntimeError(
'Failure response status from chart creation endpoint')
return parsed['url']

def get_bytes(self):
resp = self._post('https://quickchart.io/chart')
resp = self._post('%s/chart' % self.get_url_base())
return resp.content

def to_file(self, path):
content = self.get_bytes()
with open(path, 'wb') as f:
f.write(content)

3 changes: 3 additions & 0 deletions scripts/format.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash -e

poetry run autopep8 --in-place examples/*.py quickchart/*.py
34 changes: 33 additions & 1 deletion tests.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest
from datetime import datetime

from quickchart import QuickChart
from quickchart import QuickChart, QuickChartFunction

class TestQuickChart(unittest.TestCase):
def test_simple(self):
Expand Down Expand Up @@ -49,5 +50,36 @@ def test_get_bytes(self):
}
self.assertTrue(len(qc.get_bytes()) > 8000)

def test_with_function_and_dates(self):
qc = QuickChart()
qc.config = {
"type": "bar",
"data": {
"labels": [datetime(2020, 1, 15), datetime(2021, 1, 15)],
"datasets": [{
"label": "Foo",
"data": [1, 2]
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"callback": QuickChartFunction('(val) => val + "k"')
}
}],
"xAxes": [{
"ticks": {
"callback": QuickChartFunction('(val) => "$" + val')
}
}]
}
}
}

url = qc.get_url()
self.assertIn('7B%22ticks%22%3A%7B%22callback%22%3A%28val%29+%3D%3E+%22%24%22+%2B+val%7D%7D%5D%7D%7D%7D', url)
self.assertIn('2020-01-15T00%3A00%3A00', url)

if __name__ == '__main__':
unittest.main()