咱们先修改 urls.py.这文件在 Django 里的功用是把前段的 HTTP 需求和后台服务函数挂钩。在 Step3,咱们再引进后端服务函数
1 # myfirstvis/urls.py 2 from django.conf.urls import url 4 from . import views 6 urlpatterns = [ 7 url, 8 ]
在 myechartsite/urls.py 中新增 'myfirstvis.urls'
1 myechartsite/urls.py 2 from django.conf.urls import include, url 3 from django.contrib import admin 5 urlpatterns = [ 6 url, 7 url) # --- 8 ]
Step 2: 处理视图功用部分
将下列代码保存到 myfirstvis/views.py 中。
1 from __future__ import unicode_literals 2 import math 4 from django.http import HttpResponse 5 from django.template import loader 6 from pyecharts import Line3D 9 REMOTE_HOST = "https://pyecharts.github.io/assets/js" 12 def index: 13 template = loader.get_template 14 l3d = line3d 15 context = dict, 17 host=REMOTE_HOST, 18 script_list=l3d.get_js_dependencies 20 return HttpResponse) 23 def line3d: 24 _data = [] 25 for t in range: 26 _t = t / 1000 27 x = ) * math.cos 28 y = ) * math.sin 29 z = _t + 2.0 * math.sin 30 _data.append 31 range_color = [ 32 '#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', 33 '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026'] 34 line3d = Line3D 35 line3d.add 38 return line3d
cript_list 是 Page 类烘托网页所需求依靠的 echarts js 库,依靠的库的数量取决于所要烘托的图形品种。
host 是 echarts js 库的地址,默许供给的地址为 https://pyecharts.github.io/assets/js 当然,假如你乐意你也能够改动这个地址,先克隆 https://github.com/pyecharts/assets 然后将 js 文件夹挂载在你自己的服务器上即可。
Step 3: 为项目供给自己的模板
Windows 体系
在 myfirstvis 目录下,新建 templates/myfirstvis 子目录
myfirstvis 目录
─ myfirstvis ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── __init__.py ├── models.py ├── templates │ └── myfirstvis │ └── pyecharts.html ├── tests.py ├── urls.py └── views.py
将下面 html 模板代码保存为 pyecharts.html,请保证 pyecharts.html 文件的绝对路径为 project root /myfirstvis/templates/myfirstvis
1 !-- myfirstvis/templates/pyecharts.html -- 2 !DOCTYPE html 3 html 5 head 6 meta charset="utf-8" 7 title Proudly presented by PycCharts /title 8 {% for jsfile_name in script_list %} 9 script src="{{ host }}/{{ jsfile_name }}.js" /script 10 {% endfor %} 11 /head 13 body 14 {{ myechart|safe }} 15 /body 17 /html
Step 4: 运转项目
$ cd myechartsite $ python manage.py runserver You have 13 unapplied migration. Your project may not work properly until you apply the migrations for app: admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 08, 2017 - 05:48:38 Django version 1.11.4, using settings 'myechartsite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
拜访 http://localhost:8000/myfirstvis/,你就能够看到酷炫的 3D 图了


看到了吧,只需求简略的几步就能够运用 pyecharts 创立可视化的图表。Django 官方教程需求七步的这儿咱们三步就搞定了。