routes.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import sqlite3
  2. from flask_sqlalchemy import SQLAlchemy
  3. from flask import Blueprint, request, jsonify, g, current_app
  4. from .model import predict
  5. import pandas as pd
  6. # 创建蓝图 (Blueprint),用于分离路由
  7. bp = Blueprint('routes', __name__)
  8. DATABASE = 'SoilAcidification.db'
  9. def get_db():
  10. db = getattr(g, '_database', None)
  11. if db is None:
  12. db = g._database = sqlite3.connect(DATABASE)
  13. return db
  14. @bp.route('/predict', methods=['POST'])
  15. def predict_route():
  16. try:
  17. data = request.get_json()
  18. model_name = data.get('model_name') # 提取模型名称
  19. parameters = data.get('parameters', {}) # 提取所有参数
  20. input_data = pd.DataFrame([parameters]) # 转换参数为DataFrame
  21. predictions = predict(input_data, model_name) # 调用预测函数
  22. return jsonify({'predictions': predictions}), 200
  23. except Exception as e:
  24. return jsonify({'error': str(e)}), 400
  25. # 定义添加数据库记录的 API 接口
  26. @bp.route('/add_item', methods=['POST'])
  27. def add_item():
  28. """
  29. 接收 JSON 格式的请求体,包含表名和要插入的数据。
  30. 尝试将数据插入到指定的表中。
  31. :return:
  32. """
  33. db = get_db()
  34. try:
  35. # 确保请求体是JSON格式
  36. data = request.get_json()
  37. if not data:
  38. raise ValueError("No JSON data provided")
  39. table_name = data.get('table')
  40. item_data = data.get('item')
  41. if not table_name or not item_data:
  42. return jsonify({'error': 'Missing table name or item data'}), 400
  43. cur = db.cursor()
  44. # 动态构建 SQL 语句
  45. columns = ', '.join(item_data.keys())
  46. placeholders = ', '.join(['?'] * len(item_data))
  47. sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
  48. cur.execute(sql, tuple(item_data.values()))
  49. db.commit()
  50. # 返回更详细的成功响应
  51. return jsonify({'success': True, 'message': 'Item added successfully'}), 201
  52. except ValueError as e:
  53. return jsonify({'error': str(e)}), 400
  54. except KeyError as e:
  55. return jsonify({'error': f'Missing data field: {e}'}), 400
  56. except sqlite3.IntegrityError as e:
  57. # 处理例如唯一性约束违反等数据库完整性错误
  58. return jsonify({'error': 'Database integrity error', 'details': str(e)}), 409
  59. except sqlite3.Error as e:
  60. # 处理其他数据库错误
  61. return jsonify({'error': 'Database error', 'details': str(e)}), 500
  62. finally:
  63. db.close()
  64. # 定义删除数据库记录的 API 接口
  65. @bp.route('/delete_item', methods=['POST'])
  66. def delete_item():
  67. data = request.get_json()
  68. table_name = data.get('table')
  69. condition = data.get('condition')
  70. # 检查表名和条件是否提供
  71. if not table_name or not condition:
  72. return jsonify({
  73. "success": False,
  74. "message": "缺少表名或条件参数"
  75. }), 400
  76. # 尝试从条件字符串中分离键和值
  77. try:
  78. key, value = condition.split('=')
  79. except ValueError:
  80. return jsonify({
  81. "success": False,
  82. "message": "条件格式错误,应为 'key=value'"
  83. }), 400
  84. db = get_db()
  85. cur = db.cursor()
  86. try:
  87. # 执行删除操作
  88. cur.execute(f"DELETE FROM {table_name} WHERE {key} = ?", (value,))
  89. db.commit()
  90. # 如果没有错误发生,返回成功响应
  91. return jsonify({
  92. "success": True,
  93. "message": "记录删除成功"
  94. }), 200
  95. except sqlite3.Error as e:
  96. # 发生错误,回滚事务
  97. db.rollback()
  98. # 返回失败响应,并包含错误信息
  99. return jsonify({
  100. "success": False,
  101. "message": f"删除失败: {e}"
  102. }), 400
  103. # 定义修改数据库记录的 API 接口
  104. @bp.route('/update_item', methods=['PUT'])
  105. def update_record():
  106. data = request.get_json()
  107. # 检查必要的数据是否提供
  108. if not data or 'table' not in data or 'item' not in data:
  109. return jsonify({
  110. "success": False,
  111. "message": "请求数据不完整"
  112. }), 400
  113. table_name = data['table']
  114. item = data['item']
  115. # 假设 item 的第一个元素是 ID
  116. if not item or next(iter(item.keys())) is None:
  117. return jsonify({
  118. "success": False,
  119. "message": "记录数据为空"
  120. }), 400
  121. # 获取 ID 和其他字段值
  122. id_key = next(iter(item.keys()))
  123. record_id = item[id_key]
  124. updates = {key: value for key, value in item.items() if key != id_key} # 排除 ID
  125. db = get_db()
  126. cur = db.cursor()
  127. try:
  128. record_id = int(record_id) # 确保 ID 是整数
  129. except ValueError:
  130. return jsonify({
  131. "success": False,
  132. "message": "ID 必须是整数"
  133. }), 400
  134. # 准备参数列表,包括更新的值和 ID
  135. parameters = list(updates.values()) + [record_id]
  136. # 执行更新操作
  137. set_clause = ','.join([f"{k} = ?" for k in updates.keys()])
  138. sql = f"UPDATE {table_name} SET {set_clause} WHERE {id_key} = ?"
  139. try:
  140. cur.execute(sql, parameters)
  141. db.commit()
  142. if cur.rowcount == 0:
  143. return jsonify({
  144. "success": False,
  145. "message": "未找到要更新的记录"
  146. }), 404
  147. return jsonify({
  148. "success": True,
  149. "message": "数据更新成功"
  150. }), 200
  151. except sqlite3.Error as e:
  152. db.rollback()
  153. return jsonify({
  154. "success": False,
  155. "message": f"更新失败: {e}"
  156. }), 400
  157. # 定义查询数据库记录的 API 接口
  158. @bp.route('/search/record', methods=['GET'])
  159. def sql_search():
  160. """
  161. 接收 JSON 格式的请求体,包含表名和要查询的 ID。
  162. 尝试查询指定 ID 的记录并返回结果。
  163. :return:
  164. """
  165. try:
  166. data = request.get_json()
  167. # 表名
  168. sql_table = data['table']
  169. # 要搜索的 ID
  170. Id = data['id']
  171. # 连接到数据库
  172. db = get_db()
  173. cur = db.cursor()
  174. # 构造查询语句
  175. sql = f"SELECT * FROM {sql_table} WHERE id = ?"
  176. # 执行查询
  177. cur.execute(sql, (Id,))
  178. # 获取查询结果
  179. rows = cur.fetchall()
  180. column_names = [desc[0] for desc in cur.description]
  181. # 检查是否有结果
  182. if not rows:
  183. return jsonify({'error': '未查找到对应数据。'}), 400
  184. # 构造响应数据
  185. results = []
  186. for row in rows:
  187. result = {column_names[i]: row[i] for i in range(len(row))}
  188. results.append(result)
  189. # 关闭游标和数据库连接
  190. cur.close()
  191. db.close()
  192. # 返回 JSON 响应
  193. return jsonify(results), 200
  194. except sqlite3.Error as e:
  195. # 如果发生数据库错误,返回错误信息
  196. return jsonify({'error': str(e)}), 400
  197. except KeyError as e:
  198. # 如果请求数据中缺少必要的键,返回错误信息
  199. return jsonify({'error': f'缺少必要的数据字段: {e}'}), 400
  200. # 定义提供数据库列表,用于展示表格的 API 接口
  201. @bp.route('/tables', methods=['POST'])
  202. def get_table():
  203. data = request.get_json()
  204. table_name = data.get('table')
  205. if not table_name:
  206. return jsonify({'error': '需要表名'}), 400
  207. db = get_db()
  208. try:
  209. cur = db.cursor()
  210. cur.execute(f"SELECT * FROM {table_name}")
  211. rows = cur.fetchall()
  212. if not rows:
  213. return jsonify({'error': '表为空或不存在'}), 400
  214. headers = [description[0] for description in cur.description]
  215. return jsonify(rows=rows, headers=headers), 200
  216. except sqlite3.Error as e:
  217. return jsonify({'error': str(e)}), 400
  218. finally:
  219. db.close()