app.py
import pymysql
from flask import Flask,render_template,request
from Mysql 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("/show")
def show():
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))
@app.template_filter("myfilter")
def myfilter(data):
if len(data)>15:
return data[:15]+"..."
else:
return data
if __name__ == '__main__':
app.run(debug=True)
Mysql.py
import pymysql
class mysql():
def __init__(self,db="test"):
self.conn=pymysql.connect(host='127.0.0.1',port=3306,user="root",passwd="123456",db=db)
self.cursor=self.conn.cursor(pymysql.cursors.DictCursor)
def query(self, sql, args=None):
self.cursor.execute(sql, args=args)
return self.cursor.fetchall()
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()
templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="static/css/bootstrap.css">
</head>
<body>
<h2>当当网书籍信息后台统计</h2>
<p>
<a href="/show">
<span class="glyphicon glyphicon-indent-left"></span> 前五名出版数量
</a>
<span>|</span>
<a href="/">
<span class="glyphicon glyphicon-indent-left"></span> 查看书籍信息
</a>
<hr/>
</p>
{% block content %}
{% endblock %}
</body>
</html>
index.html
{% extends "base.html" %}
{% block content %}
<table class="table table-hover">
<tr>
<td class="active">编号</td>
<td class="success">书名</td>
<td class="warning">价格</td>
<td class="danger">作者</td>
<td class="info">出版社</td>
<td class="active">出版日期</td>
<td class="success">评论数</td>
</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 %}
<div id="box" style="width: 90%;height: 500px;margin: 0 auto;"></div>
<script src="static/js/echarts.min.js"></script>
<script>
mycharts=echarts.init(document.getElementById("box"))
option = {
title : {
text: '前5名出版数量',
},
tooltip : {
trigger: 'axis'
},
legend: {
data:['出版数量']
},
calculable : true,
xAxis : [
{
type : 'category',
data : {{x |safe}}
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'出版数量',
type:'bar',
data:{{y |safe}}
}
]
};
mycharts.setOption(option)
</script >
{% endblock %}