目录
一、背景
二、代码
由于系统上需要分页展示数据,并提供按字段筛选数据的功能,于是需要我写个接口,以供前端使用。
接口可以通过python flask框架实现。Flask是一个轻量级的Web框架,它提供了足够的灵活性来构建定制的RESTful API。开发者可以根据需求轻松地设计和实现接口。
数据的查询可以通过pymysql连接MySQL数据库实现。数据的筛选和分页可以通过堆叠where条件、row_number实现。
以下代码中连接的数据库用的是我电脑本地之前做学生管理系统的测试数据,可自行替换为自己的数据库、表、字段。
import flask
from flask import request
import datetime
from flask_cors import CORS
from flask import jsonify
import numpy as np
import pandas as pd
import pymysql
server=flask.Flask(__name__)
# 解决跨域请求资源被拦截问题
CORS(server,supports_credentials=True,resources=r'/*')
#从数据库读取数据
def get_data(sql,host,user,password,database,port):
conn = pymysql.connect(
host=host,
user=user,
password=password,
database=database,
port=port,
charset='utf8',
cursorclass=pymysql.cursors.DictCursor,
connect_timeout=60)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
conn.close()
cur.close()
return data
#编写SQL
def build_sql(beginTime, endTime, name, data_type, pageNum, pageSize):
conditions = []
if beginTime and endTime:
conditions.append("create_time>='{}' and create_time<='{}'".format(beginTime, endTime))
if name:
conditions.append("name like '%{}%'".format(name))
if data_type:
conditions.append("data_type='{}'".format(data_type))
where_clause = " and ".join(conditions)
sql = '''select id,name,t_class_id,create_time,data_type
from (
select id,name,t_class_id,create_time,data_type ,row_number() over(order by create_time desc ) as rn
from student_score_student
where 1=1
{}
) t
where t.rn>({}-1)*{}
and t.rn<={}*{}'''.format('and ' + where_clause if where_clause else '', pageNum, pageSize, pageNum, pageSize)
return sql
@server.route('/DataList', methods=['GET','POST'])
def warningList():
data = request.json
beginTime = data.get('beginTime')
endTime = data.get('endTime')
name = data.get('name')
data_type = data.get('data_type')
pageNum = int(data.get('pageNum', 1))
pageSize = int(data.get('pageSize', 10))
if beginTime and endTime:
try:
date_format = "%Y-%m-%d %H:%M:%S"
beginTime = datetime.strptime(beginTime, date_format).strftime(date_format)
endTime = datetime.strptime(endTime, date_format).strftime(date_format)
except Exception:
return jsonify(code='401', message='时间格式错误', data=None)
sql = build_sql(beginTime, endTime, name, data_type, pageNum, pageSize)
data = get_data(sql, 'localhost', 'root', None, 'auth_system', 3306)
data_str = [{k: str(v) if k == 'create_time' else v for k, v in d.items()} for d in data]
sql_count = "select count(1) as num from student_score_student"
num = get_data(sql_count, 'localhost', 'root', None, 'auth_system', 3306)[0]['num']
return jsonify(code='200', message='请求成功', data={'list': data_str, 'num': num})
if __name__ == '__main__':
server.run(debug=True, port=5006, host='0.0.0.0')
启动接口:
python xxx.py
测试接口:
返回数据:
{
"code": "200",
"data": {
"list": [
{
"create_time": "2023-03-06 20:15:56.916803",
"data_type": 0,
"id": 9394,
"name": "小吴1385",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.904704",
"data_type": 0,
"id": 9393,
"name": "小吴1384",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.892745",
"data_type": 0,
"id": 9392,
"name": "小吴1383",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.881069",
"data_type": 0,
"id": 9391,
"name": "小吴1382",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.869990",
"data_type": 0,
"id": 9390,
"name": "小吴1381",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.857891",
"data_type": 0,
"id": 9389,
"name": "小吴1380",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.846088",
"data_type": 0,
"id": 9388,
"name": "小吴1379",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.834624",
"data_type": 0,
"id": 9387,
"name": "小吴1378",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.823055",
"data_type": 0,
"id": 9386,
"name": "小吴1377",
"t_class_id": 24
},
{
"create_time": "2023-03-06 20:15:56.811648",
"data_type": 0,
"id": 9385,
"name": "小吴1376",
"t_class_id": 24
}
],
"num": 1292
},
"message": "请求成功"
}