二、Django 中使用 pyecharts。 前后端分离
1、安装 djangorestframework
linux pip3 install djangorestframework
windows pip install djangorestframework
2、新建一个 Django 项目
$ django-admin startproject pyecharts_django_demo_2
创建一个应用程序
$ python manage.py startapp demo
在 pyecharts_django_demo_2/settings.py 中注册应用程序
# pyecharts_django_demo_2/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo', # <--- app 名称
'rest_framework',
]
在 pyecharts_django_demo_2/urls.py 中新增 'demo.urls'
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^demo/', include('demo.urls')) #本行为新增内容
]
编辑 demo/urls.py 文件(没有就新建一个)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^bar/$', views.ChartView.as_view(), name='demo'),
url(r'^index/$', views.IndexView.as_view(), name='demo'),
]
3、 编写画图 HTML 代码
先在根目录文件夹下新建 templates 文件夹,新建一个 index.html,目录结构为
__pycache__ db.sqlite3 demo manage.py pyecharts_django_demo_2 templates
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="bar" style="1000px; height:600px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
$(
function () {
getData(chart);
}
);
function getData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/bar",
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
</script>
</body>
</html>
4: 编写 Django 和 pyecharts 代码渲染图表
将下列代码保存到 demo/views.py 中
import json
from random import randrange
from django.http import HttpResponse
from rest_framework.views import APIView
from pyecharts.charts import Bar
from pyecharts import options as opts
# Create your views here.
def response_as_json(data):
json_str = json.dumps(data)
response = HttpResponse(
json_str,
content_type="application/json",
)
response["Access-Control-Allow-Origin"] = "*"
return response
def json_response(data, code=200):
data = {
"code": code,
"msg": "success",
"data": data,
}
return response_as_json(data)
def json_error(error_string="error", code=500, **kwargs):
data = {
"code": code,
"msg": error_string,
"data": {}
}
data.update(kwargs)
return response_as_json(data)
JsonResponse = json_response
JsonError = json_error
def bar_base() -> Bar:
c = (
Bar()
.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
.add_yaxis("商家A", [randrange(0, 100) for _ in range(6)])
.add_yaxis("商家B", [randrange(0, 100) for _ in range(6)])
.set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
.dump_options()
)
return c
class ChartView(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(bar_base()))
class IndexView(APIView):
def get(self, request, *args, **kwargs):
return HttpResponse(content=open("./templates/index.html").read())
Step 4: 运行项目
$ python manage.py runserver
使用浏览器打开 http://127.0.0.1:8000/demo/index 即可访问服务
http://127.0.0.1:8000/demo/bar返回json格式的数据