学习大数据DAY35 利用 echarts 的开源图表和 python 异常处理优化网站

目录

根据分数统计电影数量来生成图表

[上机练习 14](#上机练习 14)

添加异常

添加电影类型判断是整数及正整数异常

[部署项目到 Nginx](#部署项目到 Nginx)

[上机练习 15](#上机练习 15)


根据分数统计电影数量来生成图表

Echarts 官网: https://echarts.apache.org/examples/zh/index.html
下载柱状图和饼图
可以根据需要自行选择需要的模版
flask 根据自己选择的模版准备好需要的 json 传递到 html
DAL.py 文件
def getCountByScore(self):
sql="select score,count(1) from Movie group by score"
return self.chaAll(sql)
app.py 文件
from flask import Flask,render_template,jsonify
@app.route("/zhuData")
def zhuData():
result=mdal.getCountByScore()
list1=[i[0] for i in result]
list2=[i[1] for i in result]
print(list1)
print(list2)
dict1={}
dict1["data1"]=list1
dict1["data2"]=list2
print(dict1)
return jsonify(dict1)
@app.route("/zhu")
def zhu():
return render_template("bar-background.html")
修改 bar-background.html, 首先引入 jquery 文件 , 添加异步请求代码
<script
src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript"> $.ajax({
type:"GET",
url:"http://127.0.0.1:5000/zhuData",
dataType:"json",
success:function(data){
分别修改里面的数据源为动态
data: data["data1"]
data: data["data2"]
}
});
</script>
重新加载网页,这样 html 可视化就是动态的,也成功将 Flask 和 ECharts 结
合在一起

上机练习 14

使用 echarts 完善 web 系统
显示统计报表:统计各分数的数量,使用柱状图和饼状图分别实现
效果如上两图
可以自行扩展一个自己喜欢的模版
App.py:( 业务逻辑层添加部分 )

python 复制代码
# 柱状图数据处理
@app.route("/bar-tick-align-Data")
def bar_tick_align_Data():
result=mdal.getCountByScore()
list1=[i[0] for i in result]
list2=[i[1] for i in result]
print(list1)
print(list2)
dict1={}
dict1["data1"]=list1
dict1["data2"]=list2
print(dict1)
return jsonify(dict1)
# 柱状图网页
@app.route("/bar-tick-align")
def bar_tick_align():return render_template("bar-tick-align.html")
# 饼状图数据处理
@app.route("/pie-simple-Data")
def pie_simple_Data():
result=mdal.getCountByScore()
list=[{"name":i[0],"value":i[1]} for i in result]
print(list)
return jsonify(list)
# 饼状图网页
@app.route("/pie-simple")
def pie_simple():
return render_template("pie-simple.html")

DAL.py:( 数据访问层添加部分 )

python 复制代码
# 统计各个评分的电影数量
def getCountByScore(self):
sql="select score,count(1) from DoubanMovieType group by
score"
return self.chaAll(sql)

Bar-tick-align.html:( 柱状图显示,有部分修改 )

html 复制代码
<!--
此示例下载自
https://echarts.apache.org/examples/zh/editor.html?c=bar-tick
align
-->
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
charts.min.js"></script>
<!-- Uncomment this line if you want to dataTool extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
xtension/dataTool.min.js"></script>-->
<!-- Uncomment this line if you want to use gl extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-gl/2/files/dist/ec
harts-gl.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-stat extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-stat/latest/files/
dist/ecStat.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-graph-modularity
extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-graph-modularity/2
/files/dist/echarts-graph-modularity.min.js"></script>
-->
<!-- Uncomment this line if you want to use map
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/4.9.0/files/map/js
/world.js"></script>
-->
<!-- Uncomment these two lines if you want to use bmap extension
<script type="text/javascript"
src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></sc
ript>
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
xtension/bmap.min.js"></script>
-->
<script
src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$.ajax({
type:"GET",
url:"http://127.0.0.1:5000//bar-tick-align-Data",
dataType:"json",
success:function(data){
// 分别修改里面的数据源为动态
var dom = document.getElementById('container');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',useDirtyRect: false
});
var app = {};
var option;
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: data["data1"],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Direct',
type: 'bar',
barWidth: '60%',
data: data["data2"]
}
]
};if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
}
});
</script>
</body>
</html>

Pie-simple.html:( 饼状图部分,有部分修改 )

html 复制代码
<!--
此示例下载自
https://echarts.apache.org/examples/zh/editor.html?c=pie-simpl
e
-->
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
charts.min.js"></script>
<!-- Uncomment this line if you want to dataTool extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
xtension/dataTool.min.js"></script>
-->
<!-- Uncomment this line if you want to use gl extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-gl/2/files/dist/ec
harts-gl.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-stat extension<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-stat/latest/files/
dist/ecStat.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-graph-modularity
extension
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts-graph-modularity/2
/files/dist/echarts-graph-modularity.min.js"></script>
-->
<!-- Uncomment this line if you want to use map
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/4.9.0/files/map/js
/world.js"></script>
-->
<!-- Uncomment these two lines if you want to use bmap extension
<script type="text/javascript"
src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></sc
ript>
<script type="text/javascript"
src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
xtension/bmap.min.js"></script>
-->
<script
src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$.ajax({
type:"GET",
url:"http://127.0.0.1:5000//pie-simple-Data",
dataType:"json",
success:function(data){
var dom = document.getElementById('container');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var app = {};
var option;
option = {
title: {
text: '豆瓣电影各评分电影统计',subtext: '',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: 'Access From',
type: 'pie',
radius: '50%',
data: data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
}
});
</script>
</body>
</html>

DouBanMovies.html,updateDouBanMovies.html 和 addDouBanMovie.html
修改部分:

html 复制代码
<a href="/bar-tick-align">查看柱状图</a>
<a href="/pie-simple">查看饼状图</a>

生成柱状图:

生成饼状图:

添加异常

父类的增删改方法添加异常
def edit(self,sql):
self.openDB()
result=0
try:
result=baoma.execute(sql)
conn.commit()
except Exception as e:
conn.rollback()
print(e) finally:
self.closeDB()
return result

添加电影类型判断是整数及正整数异常

@app.route("/addSubmit", methods=['POST'])
def addSubmit():
try:
tid=int(request.form.get("tid"))
if tid<=0:
raise Exception(" 编号只能输入正数 ")
except ValueError:
return " 编号只能输入整数 <a href='/add'> 刷新 </a>"
except Exception as e:
print(e)
return f"{e}<a href='/add'> 刷新 </a>"
tname=request.form.get("tname")
tcontent=request.form.get("tcontent")
mt=MovieType(tid,tname,tcontent)
result=mtdal.insert(mt)
if result==1:
return " 添加成功 <a href='/list'> 刷新 </a>"
else:
return " 添加失败 <a href='/list'> 刷新 </a>"

部署项目到 Nginx

  1. code /usr/local/nginx/conf/nginx.conf
  2. 动态网站可以使用代理转地址
    location / {
    root html;
    proxy_pass http://127.0.0.1:5000; # 请求转向
    index index.html index.htm;
    }
  3. 图表的的 ajax 地址也要修改,例如: http://192.168.159.146/zhuData
  4. 重启 Nginx 服务: /usr/local/nginx/sbin/nginx -s reload

上机练习 15

  1. 数据层 edit 添加异常,自己测试错误信息
  2. 测试添加电影类型的编号,整数(系统异常)及正整数(自定义异常)
  3. 部署到 Nginx ,通过 ip 地址来访问
    注:录制豆瓣网完整视频传到班级微信群
    DAL.py:( 添加异常处理部分 )
python 复制代码
# 数据增删改
def edit(self,sql):
try:
self.openDB()
result=baoma.execute(sql)
conn.commit()
except Exception as e:
conn.rollback()
print(e)
finally:
self.closeDB()
return result

App.py:( 添加异常处理部分 )

python 复制代码
# 添加提交
@app.route("/DouBanMovieaddSubmit", methods=["POST"])
def addSubmit():
try:
id=request.form.get("id")
title=request.form.get("title")
release_date=request.form.get("release_date")
score=request.form.get("score")
types=request.form.get("types")
if eval(id)<0 or type(eval(id))!=int:
return "id 必须为正整数 <a href='/'>刷新</a>"
if not id or not title or not release_date or not score or
not types:
return "请填写完整信息 <a href='/'>刷新</a>"
if eval(score)<0 or eval(score)>10:
return "评分必须在 0-10 之间 <a href='/'>刷新</a>"
mt=DoubanMovieType(id,title,release_date,score,types)
result=mdal.insert(mt)
if result>0:
return "添加成功 <a href='/'>刷新</a>"
else:
return "添加失败 <a href='/'>刷新</a>"
except UnboundLocalError:
return "输入数据过长! <a href='/'>刷新</a>"
except Exception as e:
print(e)
return "未知错误!请联系管理员! <a href='/'>刷新</a>"# 修改提交
@app.route("/updateDouBanMovieSubmit", methods=["POST"])
def updateSubmit():
# 修改数据
try:
old_id=request.form.get("old_id")
id=request.form.get("id")
title=request.form.get("title")
release_date=request.form.get("release_date")
score=request.form.get("score")
types=request.form.get("types")
if eval(id)<0 or type(eval(id))!=int:
return "id 必须为正整数 <a href='/'>刷新</a>"
if not id or not title or not release_date or not score or
not types:
return "请填写完整信息 <a href='/'>刷新</a>"
if eval(score)<0 or eval(score)>10:
return "评分必须在 0-10 之间 <a href='/'>刷新</a>"
result=mdal.update(old_id,"id",id)
result1=mdal.update(old_id,"title",title)
result2=mdal.update(old_id,"release_date",release_date)
result3=mdal.update(old_id,"score",score)
result4=mdal.update(old_id,"types",types)
if result or result4 or result1 or result2 or result3:
return "修改成功 <a href='/'>刷新</a>"
else:
return "修改失败 <a href='/'>刷新</a>"
except UnboundLocalError:
return "输入数据过长! <a href='/'>刷新</a>"
except Exception as e:
print(e)
return "未知错误!请联系管理员! <a href='/'>刷新</a>"

Nginx 配置成功。

经过4天的早九晚八豆瓣开发,我又一次感受到了程序员的不容易,这都是想从事IT行业要经历的。

相关推荐
量子-Alex15 分钟前
【多模态聚类】用于无标记视频自监督学习的多模态聚类网络
学习·音视频·聚类
吉大一菜鸡19 分钟前
FPGA学习(基于小梅哥Xilinx FPGA)学习笔记
笔记·学习·fpga开发
WTT00111 小时前
2024楚慧杯WP
大数据·运维·网络·安全·web安全·ctf
算法小白(真小白)2 小时前
低代码软件搭建自学第二天——构建拖拽功能
python·低代码·pyqt
唐小旭2 小时前
服务器建立-错误:pyenv环境建立后python版本不对
运维·服务器·python
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
Chinese Red Guest2 小时前
python
开发语言·python·pygame
骑个小蜗牛3 小时前
Python 标准库:string——字符串操作
python