1.在项目中创建static文件夹-------创建js文件夹-----js文件夹下放echarts.min.js(需要在echarts官网下载)
2.在项目中创建templates文件夹-------创建base.html index.html analyseinfo.html 三个html页面
app.py
from flask import Flask,render_template,request
from mysqlunit import MySql
import pandas as pd
app=Flask(__name__)
global rows
@app.route("/")
def index():
global rows
db=MySql(db="test")
sql="select * from books"
rows=db.query(sql)
print(rows)
return render_template("index.html",rows=rows)
@app.route("/tonji")
def showAnalyse():
global rows
df = pd.DataFrame(rows)
print(df)
df1 = df.groupby("Press").count()["BookId"].sort_values(ascending=False).head()
print(df1)
return render_template("analyseInfo.html", x=list(df1.index), y=list(df1))
if __name__ == '__main__':
app.run(debug=True)
mysqlunit.py
import pymysql
class MySql():
# 类的构造方法,实例化对象时,获得连接及游标
def __init__(self,db="test"):
self.conn=pymysql.connect(host='127.0.0.1',db=db,user="root",passwd="123456")
self.cursor=self.conn.cursor(pymysql.cursors.DictCursor)
# 通用查询方法,传递sql及sql中数据
def query(self,sql,args=None):
self.cursor.execute(sql,args=args)
return self.cursor.fetchall()
# 通用增删改方法,传递sql及sql中数据
def update(self,sql,args=None):
num=self.cursor.execute(sql,args=args)
self.conn.commit()
if num:
return True
else:
return False
# 关闭资源
def close(self):
self.conn.close()
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="static/css/bootstrap.css">
{% block styles %}
{% endblock %}
</head>
<body>
<h2 align="center">当当网书籍信息后台统计</h2>
<p>
<a href="/tonji">
<span class="glyphicon glyphicon-indent-left"></span> 前5名出版数量
</a>
<span>|</span>
<a href="/">
<span class="glyphicon glyphicon-th-list"></span> 查看书籍信息
</a>
<hr/>
</p>
{% block content %}
{% endblock %}
{% block scripts %}
{% endblock %}
</body>
</html>
index.html
{% extends "base.html" %}
{% block content %}
<table class="table table-striped">
<tr>
<th>编号</th>
<th>书名</th>
<th>价格</th>
<th>作者</th>
<th>出版社</th>
<th>出版日期</th>
<th>评论数</th>
</tr>
{% for row in rows %}
<tr>
<td>{{ row["BookId"] }}</td>
<td>{{ row["Title"] }}</td>
<td>{{ row["Price"] }}</td>
<td>{{ row["Author"] }}</td>
<td>{{ row["Press"] }}</td>
<td>{{ row["PubTime"] }}</td>
<td>{{ row["Comments"] }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
analyseinfo.html
{% extends "base.html" %}
{% block content %}
<script src="static\js\echarts.min.js"></script>
<div id="main" style="width: 800px;height: 400px;margin: 0 auto"></div>
<script>
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
title: {
text: '前5名出版社数量'
},
tooltip: {},
legend: {
data: ['数量']
},
xAxis: {
data: {{x | safe}}
},
yAxis: {},
series: [
{
name: '数量',
type: 'bar',
data: {{y | safe}}
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
{% endblock %}