当前位置:   article > 正文

python编写API接口实现数据筛选、查询与分页_python写api接口代码

python写api接口代码

目录

一、背景

二、代码


一、背景

由于系统上需要分页展示数据,并提供按字段筛选数据的功能,于是需要我写个接口,以供前端使用。

接口可以通过python flask框架实现。Flask是一个轻量级的Web框架,它提供了足够的灵活性来构建定制的RESTful API。开发者可以根据需求轻松地设计和实现接口。

数据的查询可以通过pymysql连接MySQL数据库实现。数据的筛选和分页可以通过堆叠where条件、row_number实现。

二、代码

以下代码中连接的数据库用的是我电脑本地之前做学生管理系统的测试数据,可自行替换为自己的数据库、表、字段。

  1. import flask
  2. from flask import request
  3. import datetime
  4. from flask_cors import CORS
  5. from flask import jsonify
  6. import numpy as np
  7. import pandas as pd
  8. import pymysql
  9. server=flask.Flask(__name__)
  10. # 解决跨域请求资源被拦截问题
  11. CORS(server,supports_credentials=True,resources=r'/*')
  12. #从数据库读取数据
  13. def get_data(sql,host,user,password,database,port):
  14. conn = pymysql.connect(
  15. host=host,
  16. user=user,
  17. password=password,
  18. database=database,
  19. port=port,
  20. charset='utf8',
  21. cursorclass=pymysql.cursors.DictCursor,
  22. connect_timeout=60)
  23. cur = conn.cursor()
  24. cur.execute(sql)
  25. data = cur.fetchall()
  26. conn.close()
  27. cur.close()
  28. return data
  29. #编写SQL
  30. def build_sql(beginTime, endTime, name, data_type, pageNum, pageSize):
  31. conditions = []
  32. if beginTime and endTime:
  33. conditions.append("create_time>='{}' and create_time<='{}'".format(beginTime, endTime))
  34. if name:
  35. conditions.append("name like '%{}%'".format(name))
  36. if data_type:
  37. conditions.append("data_type='{}'".format(data_type))
  38. where_clause = " and ".join(conditions)
  39. sql = '''select id,name,t_class_id,create_time,data_type
  40. from (
  41. select id,name,t_class_id,create_time,data_type ,row_number() over(order by create_time desc ) as rn
  42. from student_score_student
  43. where 1=1
  44. {}
  45. ) t
  46. where t.rn>({}-1)*{}
  47. and t.rn<={}*{}'''.format('and ' + where_clause if where_clause else '', pageNum, pageSize, pageNum, pageSize)
  48. return sql
  49. @server.route('/DataList', methods=['GET','POST'])
  50. def warningList():
  51. data = request.json
  52. beginTime = data.get('beginTime')
  53. endTime = data.get('endTime')
  54. name = data.get('name')
  55. data_type = data.get('data_type')
  56. pageNum = int(data.get('pageNum', 1))
  57. pageSize = int(data.get('pageSize', 10))
  58. if beginTime and endTime:
  59. try:
  60. date_format = "%Y-%m-%d %H:%M:%S"
  61. beginTime = datetime.strptime(beginTime, date_format).strftime(date_format)
  62. endTime = datetime.strptime(endTime, date_format).strftime(date_format)
  63. except Exception:
  64. return jsonify(code='401', message='时间格式错误', data=None)
  65. sql = build_sql(beginTime, endTime, name, data_type, pageNum, pageSize)
  66. data = get_data(sql, 'localhost', 'root', None, 'auth_system', 3306)
  67. data_str = [{k: str(v) if k == 'create_time' else v for k, v in d.items()} for d in data]
  68. sql_count = "select count(1) as num from student_score_student"
  69. num = get_data(sql_count, 'localhost', 'root', None, 'auth_system', 3306)[0]['num']
  70. return jsonify(code='200', message='请求成功', data={'list': data_str, 'num': num})
  71. if __name__ == '__main__':
  72. server.run(debug=True, port=5006, host='0.0.0.0')

启动接口:

python xxx.py

测试接口:

返回数据:

  1. {
  2. "code": "200",
  3. "data": {
  4. "list": [
  5. {
  6. "create_time": "2023-03-06 20:15:56.916803",
  7. "data_type": 0,
  8. "id": 9394,
  9. "name": "小吴1385",
  10. "t_class_id": 24
  11. },
  12. {
  13. "create_time": "2023-03-06 20:15:56.904704",
  14. "data_type": 0,
  15. "id": 9393,
  16. "name": "小吴1384",
  17. "t_class_id": 24
  18. },
  19. {
  20. "create_time": "2023-03-06 20:15:56.892745",
  21. "data_type": 0,
  22. "id": 9392,
  23. "name": "小吴1383",
  24. "t_class_id": 24
  25. },
  26. {
  27. "create_time": "2023-03-06 20:15:56.881069",
  28. "data_type": 0,
  29. "id": 9391,
  30. "name": "小吴1382",
  31. "t_class_id": 24
  32. },
  33. {
  34. "create_time": "2023-03-06 20:15:56.869990",
  35. "data_type": 0,
  36. "id": 9390,
  37. "name": "小吴1381",
  38. "t_class_id": 24
  39. },
  40. {
  41. "create_time": "2023-03-06 20:15:56.857891",
  42. "data_type": 0,
  43. "id": 9389,
  44. "name": "小吴1380",
  45. "t_class_id": 24
  46. },
  47. {
  48. "create_time": "2023-03-06 20:15:56.846088",
  49. "data_type": 0,
  50. "id": 9388,
  51. "name": "小吴1379",
  52. "t_class_id": 24
  53. },
  54. {
  55. "create_time": "2023-03-06 20:15:56.834624",
  56. "data_type": 0,
  57. "id": 9387,
  58. "name": "小吴1378",
  59. "t_class_id": 24
  60. },
  61. {
  62. "create_time": "2023-03-06 20:15:56.823055",
  63. "data_type": 0,
  64. "id": 9386,
  65. "name": "小吴1377",
  66. "t_class_id": 24
  67. },
  68. {
  69. "create_time": "2023-03-06 20:15:56.811648",
  70. "data_type": 0,
  71. "id": 9385,
  72. "name": "小吴1376",
  73. "t_class_id": 24
  74. }
  75. ],
  76. "num": 1292
  77. },
  78. "message": "请求成功"
  79. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/734272
推荐阅读
相关标签
  

闽ICP备14008679号