django使用pyecharts(3)----django加入echarts_定时全量更新

 


三、Django 前后端分离_定时全量更新图表
1、安装 djangorestframework
linux pip3 install djangorestframework
windows pip install djangorestframework
2、新建一个 Django 项目
$ django-admin startproject pyecharts_django_demo_3
创建一个应用程序

$ python manage.py startapp demo
在 pyecharts_django_demo_3/settings.py 中注册应用程序

# pyecharts_django_demo_3/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_3/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_3 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="line" style="width:1600px; height:800px;"></div>
<script>
var chart = echarts.init(document.getElementById('line'), 'white', {renderer: 'canvas'});

$(
function () {
getData(chart);
setInterval(getData, 2000);
}
);

function getData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/line",
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
</script>
</body>
</html>
3、编写 Django 和 pyecharts 代码渲染图表
将下列代码保存到 demo/vurls.py 和demo/views.py 中
后端代码也需要相应做出改变

编辑 demo/urls.py 文件(没有就新建一个)

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^bar/$', views.ChartViewBar.as_view(), name='bar'),
url(r'^line/$', views.ChartView.as_view(), name='line'),
url(r'^lineUpdate/$', views.ChartUpdateView.as_view(), name='lineupdate'),
url(r'^index/$', views.IndexView.as_view(), name='demo'),
]


demo.view.py

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"),
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())
Step 4: 运行项目
$ python manage.py runserver
使用浏览器打开 http://127.0.0.1:8000/demo/index 即可访问服务
http://127.0.0.1:8000/demo/line返回json格式的数据

 

上一篇:这RecyclerView的特效,看了直呼牛批


下一篇:数据可视化之pyecharts