app.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # -*- coding: utf-8 -*-
  2. from flask import Flask, jsonify, request, render_template
  3. from db_utils.data import *
  4. from db_utils.files import *
  5. from file_uploader import upload_file # 导入文件上传的函数
  6. # 初始化 Flask 应用
  7. app = Flask(__name__)
  8. # 初始化数据库和表
  9. #initialize_database()
  10. #initialize_table()
  11. # 初始化数据库和表
  12. #initialize_files_database()
  13. #initialize_files_table("filePath")
  14. @app.route('/')
  15. def home():
  16. return render_template('index.html')
  17. # 获取类别数据
  18. @app.route('/categories')
  19. def get_categories():
  20. rows = fetch_data('category')
  21. # 将查询结果格式化为字典列表
  22. category_list = [{"id": row[0], "categoryName": row[1]} for row in rows]
  23. print(category_list)
  24. # 返回 JSON 格式的数据
  25. return jsonify(category_list)
  26. @app.route('/category-data', methods=['GET'])
  27. def get_table():
  28. # 获取查询参数中的表名 (categoryName)
  29. category_name = request.args.get('categoryName')
  30. if not category_name:
  31. return jsonify({"error": "No categoryName provided"}), 400 # 如果没有提供表名,返回错误
  32. # 根据表名查询数据
  33. rows = fetch_data(category_name)
  34. if not rows:
  35. return jsonify({"error": f"No data found for table {category_name}"}), 404 # 如果没有找到数据,返回错误
  36. # 将查询结果格式化为字典列表
  37. category_list = [{"id": row[0], "categoryName": row[1], "url":row[2]} for row in rows]
  38. print(category_list)
  39. # 返回 JSON 格式的数据
  40. return jsonify(category_list)
  41. @app.route('/delete_files', methods=['DELETE'])
  42. def delete_files():
  43. # 获取 URL 查询参数
  44. file_table = request.args.get('tableName')
  45. row_id = request.args.get('rowId')
  46. # 检查是否提供了表名和记录 ID
  47. if not file_table:
  48. return jsonify({"error": "Missing table"}), 400
  49. if not row_id:
  50. return jsonify({"error": "Missing rowId"}), 400
  51. try:
  52. # 调用删除数据的函数
  53. delete_file(file_table, row_id)
  54. return jsonify({"message": f"{row_id} deleted successfully from table {file_table}!"}), 200
  55. except Exception as e:
  56. return jsonify({"error": str(e)}), 500
  57. # 上传文件接口
  58. @app.route('/upload', methods=['POST'])
  59. def upload():
  60. return upload_file() # 调用封装好的文件上传函数
  61. # 下载文件接口
  62. from flask import send_from_directory
  63. @app.route('/download/<filename>', methods=['GET'])
  64. def download_file(filename):
  65. # 强制下载文件
  66. return send_from_directory('../uploads', filename, as_attachment=True)
  67. # 运行 Flask 应用
  68. if __name__ == '__main__':
  69. app.run(host='0.0.0.0', port=5000, debug=True)