最近在学习flask框架和echarts结合使用,在网上搜到大部分都是用jquery来进行参数传递,下面我就分享一下用flask模板渲染的方式实现可视化
1.前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<link rel="shortcut icon" href="#"/>
<!-- 引入 echarts.js -->
<script src="../static/echarts.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: {{ name|safe }}
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: {{ shu }}
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
html中参数的传递需要用的是两个大括号{{}},并把参数写入其中。
大括号中的变量名是来自后端数据中字典的键名,当传过来的参数带双引号要用safe函数转义过来不然会出现如下图的编码问题
1.后端数据
from flask import Flask,render_template
app=Flask(__name__)
shu=[5, 20, 36, 10, 10, 20]
ming=["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
context={
'name':name,
'shu':shu
}
@app.route("/")
def index():
return render_template("JinJa2xuanran.html",**context)
if __name__=="__main__":
app.run()
把数据存到字典中然后在通过render_template方法传给前端
使用字典时**context传入参数(很类似C++中的二级指针),最后点击运行就可以看到展示图了