django使用pyecharts(5)----django加入echarts_增量更新_定长
五、Django 前后端分离_定时增量更新图表定长数据
1、安装 djangorestframework
linux pip3 install djangorestframework
windows pip install djangorestframework
2、新建一个 Django 项目
$ django-admin startproject pyecharts_django_demo_5
创建一个应用程序
$ python manage.py startapp demo
在 pyecharts_django_demo_5/settings.py 中注册应用程序
# pyecharts_django_demo_5/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_5/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'))
]
3、编写画图 HTML 代码
先在根目录文件夹下新建 templates 文件夹,新建一个 index.html, 定时刷新的核心在于 html 的 setInterval 方法。
文件目录情况
__pycache__ db.sqlite3 demo manage.py pyecharts_django_demo_5 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="width:1600px; height:800px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
var old_data = [];
$(
function () {
fetchData(chart);
setInterval(getDynamicData, 2000);
}
);
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/line",
dataType: "json",
success: function (result) {
var options = result.data;
chart.setOption(options);
old_data = chart.getOption().series[0].data;
}
});
}
function getDynamicData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/lineUpdate",
dataType: 'json',
success: function (result) {
var options = result.data;
old_data.push([options.name, options.value]);
old_data.shift();
chart.setOption({
series: [{
data: old_data
}],
});
},
});
}
</script>
</body>
</html>
3、编写 Django 和 pyecharts 代码渲染图表
将下列代码保存到 demo/views.py 中
后端代码也需要相应做出改变
编辑 demo/urls.py 文件(没有就新建一个)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^line/$', views.ChartView.as_view(), name='demo'),
url(r'^lineUpdate/$', views.ChartUpdateView.as_view(), name='demo'),
url(r'^index/$', views.IndexView.as_view(), name='demo'),
]
demo。view.
from django.shortcuts import render
# Create your views here.
import json
from random import randrange
from django.http import HttpResponse
from rest_framework.views import APIView
from pyecharts.charts import Line, Bar
from pyecharts import options as opts
cnt = 0 #定义line初始化时有多少组数据
# 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 line_base() -> Line:
global cnt
cnt = 9
line = (
Line()
.add_xaxis(list(range(cnt + 1)))
.add_yaxis(series_name="", y_axis=[randrange(0, 100) for _ in range(10)])
.set_global_opts(
title_opts=opts.TitleOpts(title="动态数据"),
xaxis_opts=opts.AxisOpts(type_="value",
name="时间",
),
yaxis_opts=opts.AxisOpts(type_="value")
)
.dump_options()
)
return line
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):
# print(json.loads(line_base()))
return JsonResponse(json.loads(line_base()))
class ChartViewBar(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(bar_base()))
class ChartUpdateView(APIView):
def get(self, request, *args, **kwargs):
global cnt
cnt = cnt + 1
print({"name": cnt, "value": randrange(0, 100)})
return JsonResponse({"name": cnt, "value": randrange(0, 100)})
class IndexView(APIView):
def get(self, request, *args, **kwargs):
return HttpResponse(content=open("./templates/index.html").read())
4、 运行项目
$ python manage.py runserver
使用浏览器打开 http://127.0.0.1:8000/demo/index 即可访问服务
http://127.0.0.1:8000/demo/line返回json格式的数据