diff --git a/docs/en-us/doc_advance_feature.md b/docs/en-us/doc_advance_feature.md deleted file mode 100644 index c6cb4baa..00000000 --- a/docs/en-us/doc_advance_feature.md +++ /dev/null @@ -1,137 +0,0 @@ -# pyecharts document - Advance Uage - -This artile describe some new features in V0.3.0. - -- Custom Template File -- How to Reference the Javascript file. - -## Python Script - -### Way I - -A chart render proccess can be described as the following table. - -| Step | Simple Code | remark | -| --------------------------- | ---------------------------------------- | ------ | -| 1 Create chart instance | `bar = Bar()` | | -| 2 Add the data | `bar.add(**kwargs)` | | -| 3 Create config instance | `config = PyEchartsConfig(**kwargs)` | | -| 4 Build the template engine | `engine = EchartsEnvironment(pyecharts_config=config)` | | -| 5 Load template file | `tpl = engine.get_template('demo_tpl.html')` | | -| 6 Render | `html = tpl.render(bar=bar)` | | -| 7 Write to target file | `write_utf8_html_file('my_demo_chart.html', html)` | | - -### Way II - -You can also use `render` method of chart class, with is the shortcut of way I. - -Step 1:Use `pyecharts.configure` or `pyecharts.online` to config items. - -```python -configure(jshost=None, echarts_template_dir=None, force_js_embed=None, **kwargs) -``` - -Step 2: Call the `render` method to generate HTML file. - -the method sigin for simple chart: - -```python -Chart.render(path='render.html', template_name='simple_chart.html', object_name='chart', extra_context=None) -``` - -the method sigin for page: - -```python -Page.render(path='render.html', template='simple_page.html', object='page', extra_context=None) -``` - -Each parameter marod - -- path :the file name of target HTML file. -- template_name: the file name of template. -- object_name: the variable name of chart in the template file. -- extra_context: the exra data dictionary. - -## Jupyter Notebook - -Chart class implement `_repr_html_` interface,You can directly call the instance to show the chart in a cell. - - - -## Flask - -It is easy to integrate pyechart and Flask.This is a example. - -Step 1: Create server code. - -```python -from flask import Flask -from pyecharts.engine import EchartsEnvironment -from pyecharts.conf import PyEchartsConfig - -class FlaskEchartsEnvironment(EchartsEnvironment): - def __init__(self, app, **kwargs): - EchartsEnvironment.__init__(self, **kwargs) - self.app = app - -class MyFlask(Flask): - jinja_environment = FlaskEchartsEnvironment - jinja_options = {'pyecharts_config': PyEchartsConfig( - jshost='https://cdn.bootcss.com/echarts/3.7.2', - echarts_template_dir='templates' - )} - -app = MyFlask(__name__) - -@app.route("/") -def hello(): - hm = create_heatmap() - return render_template('flask_tpl.html', hm=hm) - -def create_heatmap(): - begin = datetime.date(2017, 1, 1) - end = datetime.date(2017, 12, 31) - data = [[str(begin + datetime.timedelta(days=i)), - random.randint(1000, 25000)] for i in - range((end - begin).days + 1)] - heatmap = HeatMap("日历热力图示例", "某人 2017 年微信步数情况", width=1100) - heatmap.add("", data, is_calendar_heatmap=True, - visual_text_color='#000', visual_range_text=['', ''], - visual_range=[1000, 25000], calendar_cell_size=['auto', 30], - is_visualmap=True, calendar_date_range="2017", - visual_orient="horizontal", visual_pos="center", - visual_top="80%", is_piecewise=True) - return heatmap - - -app.run(port=10200) -``` - -Step 2:Create template file. - -```html - - - - - 自定义模板 - {{ echarts_js_dependencies(hm) }} - - -

在 Flask 下使用 echarts_* 系列模板函数(Template Functions)渲染页面。

-{{ echarts_container(hm) }} -{{ echarts_js_content(hm) }} - - -``` - -In the example,the js file of boot CDN is used, so the following code fragment is generate. - -The advance of using external link are listed as following: - -- Descrease the file size of HTML file -- More easy to integrate with web framework - -## Django - -Django use its own template engine, see the project [django-echarts](https://github.com/kinegratii/django-echarts) for more detail. \ No newline at end of file diff --git a/docs/en-us/doc_api.md b/docs/en-us/doc_api.md index bc847783..8f5cb89a 100644 --- a/docs/en-us/doc_api.md +++ b/docs/en-us/doc_api.md @@ -1,6 +1,6 @@ pyecharts API -This document describes the public API for *pyecharts* library and it will be read by developers. +This document describes the public API for *pyecharts* library and it will be read by users and developers. ## Total Proccess @@ -167,16 +167,6 @@ Convert *data* to json string, and add encoding for some specified data type: - Convert Datetime and Time objects to ISO8601 format string. - Cast numpy arrays. See the document of [astype](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html) and [tolist](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html) . -## Chart Rendering - -**JINJA2_ENV** - -`pyecharts.templates.JINJA2_ENV` - -Data type `jinja2.Environment`。pyecharts provides a build-in environment object for rendering using Jinja2 engine。 - -- This environment use *pyecharts/templates* as its base directory to store HTML and javascript files. - ## Template Engine ### Overview @@ -187,13 +177,15 @@ Data type `jinja2.Environment`。pyecharts provides a build-in environment objec ### Engine Class +`pyecharts.engine` module defines some engine class, which inherit from `jinja2.Environment`.Each class has different use case. + **BaseEnvironment** `pyecharts.engine.BaseEnvironment` -This class is the basic engine in pyecharts,and it inherits `jinja2.Environment` .It has the following features: +This class is the basic engine in pyecharts,and it inherits `jinja2.Environment` .It has the following extra features: -- Add *pyecharts_config* attribute +- Add *pyecharts_config* attribute, it is a `PyEchartsConfig` object. - Add `echarts_*` template functions This class can be used for integration with web framework. @@ -204,11 +196,19 @@ This class can be used for integration with web framework. EChartsEnvironment class inherits `BaseEnvironment` .And it use `pyecharts_config.echarts_template_dir` as the default value of template folder. +This class should not be used in web integration because of overwriting the default behavior of template file loader. + +**ECHAERTS_TEMPLATE_FUNCTIONS** + +`pyecharts.engine.ECHAERTS_TEMPLATE_FUNCTIONS` + +The dictionary containing template functions.It can be used in web integration. + ### 模板函数 -EChartsEnvironment contains some template functions, which receives a or some `Chart` / `Page` objects.See the following table. + pyecharts contains some template functions, which receives a or some `Chart` / `Page` objects as its parameter.See the following table. -| 标签/调用形式 | F(chart) | F(page) | F(chart1,chart2,...)/F(*page) | +| Function Name/Function Sign | F(chart) | F(page) | F(chart1,chart2,...)/F(*page) | | ----------------------------- | -------- | ------- | ----------------------------- | | echarts_js_dependencies | ✓ | ✓ | ✓ | | echarts_js_dependencies_embed | ✓ | ✓ | ✓ | diff --git a/docs/en-us/doc_web_integration.md b/docs/en-us/doc_web_integration.md new file mode 100644 index 00000000..8854dead --- /dev/null +++ b/docs/en-us/doc_web_integration.md @@ -0,0 +1,114 @@ +# pyecharts document - Web Integration + +> Before You Read +> +> 1. This web integration requires pyecharts V0.3.0+. +> 2. This article is principle-described instead of a tutorial.So you should learn a lot about the relevant web framework. + +Now, it is more easy to integrate pyecharts with your web framework ,whatever you start a project or integrate a exist one.The integration will not break down origin features because of the flexibility and OOP in Python language. + +pyecharts exposes the API of builtin jinja2 template engine.In theory, it is easy to integrate the web framework which use jinja2 template engine. + +In different use case,different specific methods and procedures will be used. This arctile will use the common framework,Django and Flask to describe the procedures ,which other framework can be inspired from. + +## Flask + +### Custom Template Engine + +pyecharts use jinja2 as its template engine.According to Flask document.It is easy to integrate pyechart and Flask.This is a example. + +You can follow these steps to create custom template engine. + +- In the constructor `__init__` , addd attribute `pyecharts_config` and add template functions. +- Assign this class to your Flask app class. + +```python +from flask import Flask, render_template +from flask.templating import Environment + +from pyecharts import HeatMap +from pyecharts.engine import ECHAERTS_TEMPLATE_FUNCTIONS +from pyecharts.conf import PyEchartsConfig + +class FlaskEchartsEnvironment(Environment): + def __init__(self, *args, **kwargs): + super(FlaskEchartsEnvironment, self).__init__(*args, **kwargs) + self.pyecharts_config = PyEchartsConfig(jshost='https://cdn.bootcss.com/echarts/3.7.2') + self.globals.update(ECHAERTS_TEMPLATE_FUNCTIONS) + +class MyFlask(Flask): + jinja_environment = FlaskEchartsEnvironment + +app = MyFlask(__name__) +``` + +### Template Function + +You can use `echarts_*` template function in the template file. + +```html + + + + + 自定义模板 + {{ echarts_js_dependencies(hm) }} + + +

在 Flask 下使用 echarts_* 系列模板函数(Template Functions)渲染页面。

+ {{ echarts_container(hm) }} + {{ echarts_js_content(hm) }} + + +``` + +In the demo, boo CDN js is used, so the output ` +``` + +### Example Project + +The github repositoriy [Flask_demo](https://github.com/kinegratii/flask_demo) is a more complete example, which use local echarts library javascript files.You can continue development based on this project. + +## Django + +### Custom Template Engine + +From v1.8, you can directly use jinja2 as template engine in Django. + +In the integration,you should define a callable function which returns a `jinja2.Environment` object.This is a example following [Django Document](https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2) : + +```python +from django.contrib.staticfiles.storage import staticfiles_storage +from django.urls import reverse + +from pyecharts.conf import PyEchartsConfig +from pyecharts.engine import BaseEnvironment + + +def environment(**options): + env = BaseEnvironment(pyecharts_config=PyEchartsConfig(jshost='/static/'), **options) + # Add template functions to the environment object + env.globals.update({ + 'static': staticfiles_storage.url, + 'url': reverse, + }) + return env + +``` + +See more detail at Django document. + +## Summary + +You can has two way to create your own engine class. + +- Inherit `pyecharts.engine.BaseEnvironment` :e.g Django. Used for用于可以直接使用的场景。 +- Add template function:e.g Flask, The class `flask.templating.Environment` overwrites some features from `jinja2.Environment` .So you should inherit this class,and add template function handly. + +## More + +- If you use Django's default template engine, see the project [django-echarts](https://github.com/kinegratii/django-echarts) for more detail. + diff --git a/docs/zh-cn/doc_advance_feature.md b/docs/zh-cn/doc_advance_feature.md deleted file mode 100644 index 3ae056b3..00000000 --- a/docs/zh-cn/doc_advance_feature.md +++ /dev/null @@ -1,155 +0,0 @@ -# pyecharts 文档 - 高级使用篇 - -本文描述了 v0.3.0 新引入的特性: - -- 自定义模板文件 -- 决定 script 标签的引入方式,即 **内嵌** 和 **外链** 两种方式。 - -V0.3.0 重写了部分底层代码,支持更多使用场景。 - -## 脚本环境 - -### 方式一 - -一个图表的渲染过程可以描述如下,遵循 “先配置,后执行” 的标准流程。 - -| 步骤 | 简略代码 | 备注 | -| -------- | ---------------------------------------- | ---- | -| 1 创建图表实例 | `bar = Bar()` | | -| 2 添加数据 | `bar.add(**kwargs)` | | -| 3 创建配置实例 | `config = PyEchartsConfig(**kwargs)` | | -| 4 构建模板引擎 | `engine = EchartsEnvironment(pyecharts_config=config)` | | -| 5 获取模板文件 | `tpl = engine.get_template('demo_tpl.html')` | | -| 6 渲染 | `html = tpl.render(bar=bar)` | | -| 7 写入目标文件 | `write_utf8_html_file('my_demo_chart.html', html)` | | - -### 方式二 - -第二种方式是直接使用图表的 `render` 方法,此种方式为第一方式的快捷方式。 - -第一步使用 `pyecharts.configure` 或者 `pyecharts.online` 进行配置。 - -```python -configure(jshost=None, - echarts_template_dir=None, - force_js_embed=None, - **kwargs) -``` - -第二步,调用图表类的函数 `render` 方法,生成 HTML 文件。 - -单图表 `render` 方法函数签名: - -```python -Chart.render(path='render.html', - template_name='simple_chart.html', - object_name='chart', - extra_context=None) -``` - -多图表 `render` 方法签名: - -```python -Page.render(path='render.html', - template='simple_page.html', - object='page', - extra_context=None) -``` - -各参数意义如下: - -- path :最终生成文件名称 -- template_name: 模板文件名称,其目录可通过 `pyecharts.configure()` 全局函数进行配置 -- object_name: 模板文件中,该图表类所使用变量的名称 -- extra_context 额外数据字典。 - -## Jupyter Notebook - -pyecharts 的图表类实现了 `_repr_html_` 接口,支持在 Cell 中显示渲染结果,只需直接调用自身实例即可。 - - - -## Flask 框架 - -由于 pyecharts 默认采用 Jinja2 作为模板引擎,因此非常容易与 Flask 进行整合。下面是进行整合的一个例子。 - -第一步,编写后台代码: - -```python -from flask import Flask -from pyecharts.engine import EchartsEnvironment -from pyecharts.conf import PyEchartsConfig - -class FlaskEchartsEnvironment(EchartsEnvironment): - def __init__(self, app, **kwargs): - EchartsEnvironment.__init__(self, **kwargs) - self.app = app - -class MyFlask(Flask): - jinja_environment = FlaskEchartsEnvironment - jinja_options = {'pyecharts_config': PyEchartsConfig( - jshost='https://cdn.bootcss.com/echarts/3.7.2', - echarts_template_dir='templates' - )} - -app = MyFlask(__name__) - -@app.route("/") -def hello(): - hm = create_heatmap() - return render_template('flask_tpl.html', hm=hm) - -def create_heatmap(): - begin = datetime.date(2017, 1, 1) - end = datetime.date(2017, 12, 31) - data = [[str(begin + datetime.timedelta(days=i)), - random.randint(1000, 25000)] for i in - range((end - begin).days + 1)] - heatmap = HeatMap("日历热力图示例", "某人 2017 年微信步数情况", width=1100) - heatmap.add("", data, is_calendar_heatmap=True, - visual_text_color='#000', visual_range_text=['', ''], - visual_range=[1000, 25000], calendar_cell_size=['auto', 30], - is_visualmap=True, calendar_date_range="2017", - visual_orient="horizontal", visual_pos="center", - visual_top="80%", is_piecewise=True) - return heatmap - - -app.run(port=10200) - -``` - -只需继承 `flask.Flask` 类并指定 `pyecharts.engine.EchartsEnvironment` 为默认的模板渲染引擎。 - -第二步,编写模板文件:在同目录下 templates 文件夹中。 - -```html - - - - - 自定义模板 - {{ echarts_js_dependencies(hm) }} - - -

在 Flask 下使用 echarts_* 系列模板函数(Template Functions)渲染页面。

- {{ echarts_container(hm) }} - {{ echarts_js_content(hm) }} - - -``` - -由于上述例子使用 boot CDN 的 js 文件,因此在最后生成 HTML 文件代码时,使用了下面的外链形式 - -```html - -``` - -使用外链形式优点在于: - -- 减少最后生成文件大小 -- 更容易与 web 框架整合,便于大型项目开发 - -## Django 框架 - -Django 使用了自己的模板引擎,可参考 [django-echarts](https://github.com/kinegratii/django-echarts) 项目。 diff --git a/docs/zh-cn/doc_api.md b/docs/zh-cn/doc_api.md index 2fa9a497..616ce8f6 100644 --- a/docs/zh-cn/doc_api.md +++ b/docs/zh-cn/doc_api.md @@ -155,7 +155,7 @@ for chart in page: * cast - `pyecharts.base.cast(seq)` + `pyecharts.base.Base.cast(seq)` 数据格式化处理函数,能够将源数据转化为符合 pyecharts 的数据。 @@ -188,14 +188,16 @@ pyecharts库使用 [Jinja2](http://jinja.pocoo.org/) 作为其默认模板渲染 ### 引擎对象 +`pyecharts.engine` 定义了若干个继承自 `jinja2.Environment` 的模板引擎类,每个类都有其适合的使用场景。 + **BaseEnvironment** `pyecharts.engine.BaseEnvironment` 该类是 pyecharts 基本的模板引擎类,该类直接继承 `jinja2.Environment` ,并且: -- 拥有 pyecharts_config 配置对象 -- 添加了 `echarts_*` 等模板函数 +- 添加了 pyecharts_config 属性,这是一个 `PyEchartsConfig` 对象。 +- 添加了 `echarts_*` 等模板函数。 该类可用于 web 框架整合。 @@ -205,9 +207,17 @@ pyecharts库使用 [Jinja2](http://jinja.pocoo.org/) 作为其默认模板渲染 EChartsEnvironment 类继承自 `BaseEnvironment` 。并在此基础上改写了模板文件加载器(loader)的行为,默认使用 `pyecharts_config.echarts_template_dir` 作为模板文件目录。 +由于该类重写模板文件加载器的行为,因此不应当用于 web 整合。 + +**ECHAERTS_TEMPLATE_FUNCTIONS** + +`pyecharts.engine.ECHAERTS_TEMPLATE_FUNCTIONS` + +包含模板函数的字典。可用于 web 框架整合。 + ### 模板函数 -EChartsEnvironment 引擎提供了一些模板函数,这些函数通常接收一个或多个的 `Chart` 或 `Page` 的参数,详细的调用形式见下表。 +pyecharts 内置的引擎提供了一些模板函数,这些函数通常接收一个或多个的 `Chart` 或 `Page` 的参数,详细的调用形式见下表。 | 标签/调用形式 | F(chart) | F(page) | F(chart1,chart2,...)/F(*page) | | ----------------------------- | -------- | ------- | ----------------------------- | diff --git a/docs/zh-cn/doc_web_integration.md b/docs/zh-cn/doc_web_integration.md new file mode 100644 index 00000000..7beb1213 --- /dev/null +++ b/docs/zh-cn/doc_web_integration.md @@ -0,0 +1,119 @@ +# pyecharts 文档 - web整合篇 + +> 阅读指引: +> +> 1. 本文所述的整合方式适用于 V0.3.0及其以上的版本。 +> 2. 本文不是一个教程性质的文档,仅描述关键步骤和原理文档。因此在阅读之前,你应当对相关的web 框架有所了解或者参考示例项目。 + +pyecharts 现在和 web 框架的整合工作变得十分容易,无论你是刚开始开发 web 项目还是整合已有的项目。这主要得益于 python 语言的灵活性和面向对象特点,使得整合工作不会破坏原有的功能和代码层次结构。 + +pyecharts 已经开放内部的 jinja2 模板引擎相关接口,因此从理论上来说,pyecharts 能够胜任那些使用 jinja2 模板引擎的 web 框架。 + +整合工作依据不同的框架和使用场景有不同的具体方法。本文将以 Django 和 Flask 这两个主流框架描述不同方式的整合过程,其他 web 框架可以以此为参考。 + +## Flask + +### 自定义模板引擎 + +Flask 默认采用 jinja2 作为其模板引擎。根据 Flask 文档,可以在 `Flask.jinja_environment` ,指定自己实现的模板引擎类,以实现特定功能。 + +在 Flask 中可按下列步骤实现自己的模板引擎类: + +- 创建一个继承自 `flask.templating.Environment` 的模板引擎类`FlaskEchartsEnvironment` 。 +- 在构造函数 `__init__` 中,为该类添加 `pyecharts_config` 属性, 添加模板函数到全局字典中。 +- 在自己的 Flask 应用类中指定 `FlaskEchartsEnvironment` 为默认模板引擎。 + +```python +from flask import Flask, render_template +from flask.templating import Environment + +from pyecharts import HeatMap +from pyecharts.engine import ECHAERTS_TEMPLATE_FUNCTIONS +from pyecharts.conf import PyEchartsConfig + +class FlaskEchartsEnvironment(Environment): + def __init__(self, *args, **kwargs): + super(FlaskEchartsEnvironment, self).__init__(*args, **kwargs) + self.pyecharts_config = PyEchartsConfig(jshost='https://cdn.bootcss.com/echarts/3.7.2') + self.globals.update(ECHAERTS_TEMPLATE_FUNCTIONS) + +class MyFlask(Flask): + jinja_environment = FlaskEchartsEnvironment + +app = MyFlask(__name__) +``` + +### 模板函数 + +在模板文件中可以使用 `echarts_*` 系列模板函数。 + +```html + + + + + 自定义模板 + {{ echarts_js_dependencies(hm) }} + + +

在 Flask 下使用 echarts_* 系列模板函数(Template Functions)渲染页面。

+ {{ echarts_container(hm) }} + {{ echarts_js_content(hm) }} + + +``` + +上述例子使用 boot CDN 的 js 文件,因此在最后生成 HTML 文件代码时,使用了下面的外链形式 + +```html + +``` + +使用外链形式优点在于: + +- 减少最后生成文件大小 +- 更容易与 web 框架整合,便于大型项目开发 + +### 示例项目 + +示例项目可参考 [Flask_demo](https://github.com/kinegratii/flask_demo), 该项目完全使用本地 echarts 文件。可基于该项目继续开发。 + +## Django + +### 自定义模板引擎 + +自 v1.8 起,Django 支持多模板引擎,内置了对 Jinja2 的支持。pyecharts 内部也是使用 Jinja2 作为其默认的模板引擎。因此二者的整合是非常简单的。 + +首先,需要实现一个返回一个 `jinja2.Environment` 对象的回调函数。下面是仿造 [官方例子](https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2) 实现的一个例子: + +```python +from django.contrib.staticfiles.storage import staticfiles_storage +from django.urls import reverse + +from pyecharts.conf import PyEchartsConfig +from pyecharts.engine import BaseEnvironment + + +def environment(**options): + env = BaseEnvironment(pyecharts_config=PyEchartsConfig(jshost='/static/'), **options) + # Add template functions to the environment object + env.globals.update({ + 'static': staticfiles_storage.url, + 'url': reverse, + }) + return env + +``` + +其余按照 Django 文档配置 `settings.TEMPLATES` 等变量值。 + +## 总结 + +在整合过程中,主要有两种方式实现自己的模板引擎类: + +- 直接继承 `pyecharts.engine.BaseEnvironment` :如 Django。用于可以直接使用的场景。 +- 手动添加模板函数:如 Flask ,Flask 引擎类`flask.templating.Environment` 重写了 `jinja2.Environment` 相关逻辑,因此应当继承该类,并且手动添加相关模板函数 + +## 其他 + +- 关于Django 使用了自己的模板引擎,可参考 [django-echarts](https://github.com/kinegratii/django-echarts) 项目。 \ No newline at end of file diff --git a/pyecharts/engine.py b/pyecharts/engine.py index 638c5551..63ad175e 100644 --- a/pyecharts/engine.py +++ b/pyecharts/engine.py @@ -170,17 +170,13 @@ ECHAERTS_TEMPLATE_FUNCTIONS = { } -class PyEchartsConfigMixin(object): - pyecharts_config = None - - -class BaseEnvironment(Environment, PyEchartsConfigMixin): +class BaseEnvironment(Environment): """ Add config and echarts template functions to a Environment object. """ def __init__(self, *args, **kwargs): - self.pyecharts_config = kwargs.pop('pyecharts_config', self.pyecharts_config) + self.pyecharts_config = kwargs.pop('pyecharts_config', None) if self.pyecharts_config is None: raise TypeError('no pyecharts_config for this environment specified') super(BaseEnvironment, self).__init__(*args, **kwargs)