当前位置:   article > 正文

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

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

目录

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

上机练习 14

添加异常

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

部署项目到 Nginx

上机练习 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:( 业务逻辑层添加部分 )
  1. # 柱状图数据处理
  2. @app.route("/bar-tick-align-Data")
  3. def bar_tick_align_Data():
  4. result=mdal.getCountByScore()
  5. list1=[i[0] for i in result]
  6. list2=[i[1] for i in result]
  7. print(list1)
  8. print(list2)
  9. dict1={}
  10. dict1["data1"]=list1
  11. dict1["data2"]=list2
  12. print(dict1)
  13. return jsonify(dict1)
  14. # 柱状图网页
  15. @app.route("/bar-tick-align")
  16. def bar_tick_align():return render_template("bar-tick-align.html")
  17. # 饼状图数据处理
  18. @app.route("/pie-simple-Data")
  19. def pie_simple_Data():
  20. result=mdal.getCountByScore()
  21. list=[{"name":i[0],"value":i[1]} for i in result]
  22. print(list)
  23. return jsonify(list)
  24. # 饼状图网页
  25. @app.route("/pie-simple")
  26. def pie_simple():
  27. return render_template("pie-simple.html")
DAL.py:( 数据访问层添加部分 )
  1. # 统计各个评分的电影数量
  2. def getCountByScore(self):
  3. sql="select score,count(1) from DoubanMovieType group by
  4. score"
  5. return self.chaAll(sql)
Bar-tick-align.html:( 柱状图显示,有部分修改 )
  1. <!--
  2. 此示例下载自
  3. https://echarts.apache.org/examples/zh/editor.html?c=bar-tick
  4. align
  5. -->
  6. <!DOCTYPE html>
  7. <html lang="en" style="height: 100%">
  8. <head>
  9. <meta charset="utf-8">
  10. </head>
  11. <body style="height: 100%; margin: 0">
  12. <div id="container" style="height: 100%"></div>
  13. <script type="text/javascript"
  14. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  15. charts.min.js"></script>
  16. <!-- Uncomment this line if you want to dataTool extension
  17. <script type="text/javascript"
  18. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  19. xtension/dataTool.min.js"></script>-->
  20. <!-- Uncomment this line if you want to use gl extension
  21. <script type="text/javascript"
  22. src="https://registry.npmmirror.com/echarts-gl/2/files/dist/ec
  23. harts-gl.min.js"></script>
  24. -->
  25. <!-- Uncomment this line if you want to echarts-stat extension
  26. <script type="text/javascript"
  27. src="https://registry.npmmirror.com/echarts-stat/latest/files/
  28. dist/ecStat.min.js"></script>
  29. -->
  30. <!-- Uncomment this line if you want to echarts-graph-modularity
  31. extension
  32. <script type="text/javascript"
  33. src="https://registry.npmmirror.com/echarts-graph-modularity/2
  34. /files/dist/echarts-graph-modularity.min.js"></script>
  35. -->
  36. <!-- Uncomment this line if you want to use map
  37. <script type="text/javascript"
  38. src="https://registry.npmmirror.com/echarts/4.9.0/files/map/js
  39. /world.js"></script>
  40. -->
  41. <!-- Uncomment these two lines if you want to use bmap extension
  42. <script type="text/javascript"
  43. src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></sc
  44. ript>
  45. <script type="text/javascript"
  46. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  47. xtension/bmap.min.js"></script>
  48. -->
  49. <script
  50. src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  51. <script type="text/javascript">
  52. $.ajax({
  53. type:"GET",
  54. url:"http://127.0.0.1:5000//bar-tick-align-Data",
  55. dataType:"json",
  56. success:function(data){
  57. // 分别修改里面的数据源为动态
  58. var dom = document.getElementById('container');
  59. var myChart = echarts.init(dom, null, {
  60. renderer: 'canvas',useDirtyRect: false
  61. });
  62. var app = {};
  63. var option;
  64. option = {
  65. tooltip: {
  66. trigger: 'axis',
  67. axisPointer: {
  68. type: 'shadow'
  69. }
  70. },
  71. grid: {
  72. left: '3%',
  73. right: '4%',
  74. bottom: '3%',
  75. containLabel: true
  76. },
  77. xAxis: [
  78. {
  79. type: 'category',
  80. data: data["data1"],
  81. axisTick: {
  82. alignWithLabel: true
  83. }
  84. }
  85. ],
  86. yAxis: [
  87. {
  88. type: 'value'
  89. }
  90. ],
  91. series: [
  92. {
  93. name: 'Direct',
  94. type: 'bar',
  95. barWidth: '60%',
  96. data: data["data2"]
  97. }
  98. ]
  99. };if (option && typeof option === 'object') {
  100. myChart.setOption(option);
  101. }
  102. window.addEventListener('resize', myChart.resize);
  103. }
  104. });
  105. </script>
  106. </body>
  107. </html>

Pie-simple.html:( 饼状图部分,有部分修改 )
  1. <!--
  2. 此示例下载自
  3. https://echarts.apache.org/examples/zh/editor.html?c=pie-simpl
  4. e
  5. -->
  6. <!DOCTYPE html>
  7. <html lang="en" style="height: 100%">
  8. <head>
  9. <meta charset="utf-8">
  10. </head>
  11. <body style="height: 100%; margin: 0">
  12. <div id="container" style="height: 100%"></div>
  13. <script type="text/javascript"
  14. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  15. charts.min.js"></script>
  16. <!-- Uncomment this line if you want to dataTool extension
  17. <script type="text/javascript"
  18. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  19. xtension/dataTool.min.js"></script>
  20. -->
  21. <!-- Uncomment this line if you want to use gl extension
  22. <script type="text/javascript"
  23. src="https://registry.npmmirror.com/echarts-gl/2/files/dist/ec
  24. harts-gl.min.js"></script>
  25. -->
  26. <!-- Uncomment this line if you want to echarts-stat extension<script type="text/javascript"
  27. src="https://registry.npmmirror.com/echarts-stat/latest/files/
  28. dist/ecStat.min.js"></script>
  29. -->
  30. <!-- Uncomment this line if you want to echarts-graph-modularity
  31. extension
  32. <script type="text/javascript"
  33. src="https://registry.npmmirror.com/echarts-graph-modularity/2
  34. /files/dist/echarts-graph-modularity.min.js"></script>
  35. -->
  36. <!-- Uncomment this line if you want to use map
  37. <script type="text/javascript"
  38. src="https://registry.npmmirror.com/echarts/4.9.0/files/map/js
  39. /world.js"></script>
  40. -->
  41. <!-- Uncomment these two lines if you want to use bmap extension
  42. <script type="text/javascript"
  43. src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></sc
  44. ript>
  45. <script type="text/javascript"
  46. src="https://registry.npmmirror.com/echarts/5.5.1/files/dist/e
  47. xtension/bmap.min.js"></script>
  48. -->
  49. <script
  50. src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  51. <script type="text/javascript">
  52. $.ajax({
  53. type:"GET",
  54. url:"http://127.0.0.1:5000//pie-simple-Data",
  55. dataType:"json",
  56. success:function(data){
  57. var dom = document.getElementById('container');
  58. var myChart = echarts.init(dom, null, {
  59. renderer: 'canvas',
  60. useDirtyRect: false
  61. });
  62. var app = {};
  63. var option;
  64. option = {
  65. title: {
  66. text: '豆瓣电影各评分电影统计',subtext: '',
  67. left: 'center'
  68. },
  69. tooltip: {
  70. trigger: 'item'
  71. },
  72. legend: {
  73. orient: 'vertical',
  74. left: 'left'
  75. },
  76. series: [
  77. {
  78. name: 'Access From',
  79. type: 'pie',
  80. radius: '50%',
  81. data: data,
  82. emphasis: {
  83. itemStyle: {
  84. shadowBlur: 10,
  85. shadowOffsetX: 0,
  86. shadowColor: 'rgba(0, 0, 0, 0.5)'
  87. }
  88. }
  89. }
  90. ]
  91. };
  92. if (option && typeof option === 'object') {
  93. myChart.setOption(option);
  94. }
  95. window.addEventListener('resize', myChart.resize);
  96. }
  97. });
  98. </script>
  99. </body>
  100. </html>
DouBanMovies.html,updateDouBanMovies.html addDouBanMovie.html
修改部分:
  1. <a href="/bar-tick-align">查看柱状图</a>
  2. <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:( 添加异常处理部分 )
  1. # 数据增删改
  2. def edit(self,sql):
  3. try:
  4. self.openDB()
  5. result=baoma.execute(sql)
  6. conn.commit()
  7. except Exception as e:
  8. conn.rollback()
  9. print(e)
  10. finally:
  11. self.closeDB()
  12. return result
App.py:( 添加异常处理部分 )
  1. # 添加提交
  2. @app.route("/DouBanMovieaddSubmit", methods=["POST"])
  3. def addSubmit():
  4. try:
  5. id=request.form.get("id")
  6. title=request.form.get("title")
  7. release_date=request.form.get("release_date")
  8. score=request.form.get("score")
  9. types=request.form.get("types")
  10. if eval(id)<0 or type(eval(id))!=int:
  11. return "id 必须为正整数 <a href='/'>刷新</a>"
  12. if not id or not title or not release_date or not score or
  13. not types:
  14. return "请填写完整信息 <a href='/'>刷新</a>"
  15. if eval(score)<0 or eval(score)>10:
  16. return "评分必须在 0-10 之间 <a href='/'>刷新</a>"
  17. mt=DoubanMovieType(id,title,release_date,score,types)
  18. result=mdal.insert(mt)
  19. if result>0:
  20. return "添加成功 <a href='/'>刷新</a>"
  21. else:
  22. return "添加失败 <a href='/'>刷新</a>"
  23. except UnboundLocalError:
  24. return "输入数据过长! <a href='/'>刷新</a>"
  25. except Exception as e:
  26. print(e)
  27. return "未知错误!请联系管理员! <a href='/'>刷新</a>"# 修改提交
  28. @app.route("/updateDouBanMovieSubmit", methods=["POST"])
  29. def updateSubmit():
  30. # 修改数据
  31. try:
  32. old_id=request.form.get("old_id")
  33. id=request.form.get("id")
  34. title=request.form.get("title")
  35. release_date=request.form.get("release_date")
  36. score=request.form.get("score")
  37. types=request.form.get("types")
  38. if eval(id)<0 or type(eval(id))!=int:
  39. return "id 必须为正整数 <a href='/'>刷新</a>"
  40. if not id or not title or not release_date or not score or
  41. not types:
  42. return "请填写完整信息 <a href='/'>刷新</a>"
  43. if eval(score)<0 or eval(score)>10:
  44. return "评分必须在 0-10 之间 <a href='/'>刷新</a>"
  45. result=mdal.update(old_id,"id",id)
  46. result1=mdal.update(old_id,"title",title)
  47. result2=mdal.update(old_id,"release_date",release_date)
  48. result3=mdal.update(old_id,"score",score)
  49. result4=mdal.update(old_id,"types",types)
  50. if result or result4 or result1 or result2 or result3:
  51. return "修改成功 <a href='/'>刷新</a>"
  52. else:
  53. return "修改失败 <a href='/'>刷新</a>"
  54. except UnboundLocalError:
  55. return "输入数据过长! <a href='/'>刷新</a>"
  56. except Exception as e:
  57. print(e)
  58. return "未知错误!请联系管理员! <a href='/'>刷新</a>"
Nginx 配置成功。
经过4天的早九晚八豆瓣开发,我又一次感受到了程序员的不容易,这都是想从事IT行业要经历的。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/967252
推荐阅读
相关标签
  

闽ICP备14008679号