python flask项目:python读取数据库sales_quarter = "select monthly,total_price from goods_train",其中monthly为日期(YYYY/MM形式),定义data[],将里面的monthly转换为季度date为单位并求出每年每季度的销售总额sales,然后将求出的date和sales存入data[],然后然后以json格式返回,在根据返回的data的数据用ajax赋值到echarts柱状图里,写出代码
时间: 2024-02-12 20:03:11 浏览: 76
好的,下面是代码实现:
```python
from flask import Flask, jsonify
import json
import pymysql
app = Flask(__name__)
@app.route('/sales_data', methods=['GET'])
def get_sales_data():
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='123456', db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
# 查询每年每季度的销售总额
sales_quarter = "SELECT YEAR(monthly) AS year, CONCAT(YEAR(monthly), '-', QUARTER(monthly)) AS quarter, SUM(total_price) AS sales FROM goods_train GROUP BY YEAR(monthly), QUARTER(monthly)"
cursor.execute(sales_quarter)
results = cursor.fetchall()
# 将结果存入data列表
data = []
for result in results:
data.append({'date': result['quarter'], 'sales': result['sales']})
# 返回json格式数据
return jsonify(data)
if __name__ == '__main__':
app.run()
```
接着在前端页面上使用ajax请求sales_data接口,获取到返回的json数据,然后使用echarts绘制柱状图即可。下面是前端页面的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>销售数据柱状图</title>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.7.0/echarts.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 800px;height:400px;"></div>
<script>
$(document).ready(function(){
// 发送ajax请求获取销售数据
$.ajax({
url: '/sales_data',
type: 'GET',
success: function(res){
// 将返回的json数据转换为echarts所需的格式
var date = [];
var sales = [];
for (var i = 0; i < res.length; i++) {
date.push(res[i].date);
sales.push(res[i].sales);
}
// 使用echarts绘制柱状图
var chart = echarts.init(document.getElementById('chart'));
var option = {
title: {
text: '销售数据柱状图'
},
tooltip: {},
legend: {
data: ['销售额']
},
xAxis: {
data: date
},
yAxis: {},
series: [{
name: '销售额',
type: 'bar',
data: sales
}]
};
chart.setOption(option);
}
});
});
</script>
</body>
</html>
```
以上代码仅供参考,具体实现可能需要根据实际情况进行修改。
阅读全文