Django后端实现基于ajax的pyecharts动态加载
背景
后端:Django,前端:HTML,主要利用库pyecharts,然后实现前后端分离加载图表
参考官网文档的Django案例写下,参考网址:https://pyecharts.org/#/zh-cn/web_django
这里我重新创建一个Django项目
创建完项目如图
装pyecharts库
在terminal输入以下字符
pip3 install pyecharts
这里我已经装过了
测试一下是否正常
在terminal输入以下字符
python3 manage.py runserver
terminal
浏览器
新建一个app,名为adamBlog(建议别修改,跟我一样)
在terminal输入
python3 manage.py startapp adamBlog
在Django项目的settings.py文件中把app注册
项目的urls.py文件下增加以下内容
"""ajax_django_pyecharts URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import re_path
from adamBlog import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^my_first_home/$', views.home_page),
re_path(r'^bar/$', views.ChartView.as_view()),
]
找到刚刚创建的app->views.py
输入以下内容
from django.shortcuts import render
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_demo() -> 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_with_quotes()
)
return c
class ChartView(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(bar_demo()))
def home_page(request):
return render(request,'my_home.html',{})
找到templates文件夹,如果没有创建一个(位置在项目的根目录)
在templates目录下创建一个html文件,名为my_home.html
内容如下
<html>
<head>
<meta charset="UTF-8">
<title>echarts-ajax</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:1000px; height:600px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
$(
function () {
fetchData(chart);
}
);
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/bar",
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
</script>
</body>
</html>
至此就完成工作,我们再启动Django的服务。
在terminal输入以下字符
python3 manage.py runserver