app.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from flask import Flask, jsonify, request,send_from_directory
  2. from flask_cors import CORS
  3. import os
  4. import sqlite3
  5. import uuid
  6. app = Flask(__name__)
  7. CORS(app)
  8. # 图片上传目录
  9. UPLOAD_FOLDER = 'uploads'
  10. if not os.path.exists(UPLOAD_FOLDER):
  11. os.makedirs(UPLOAD_FOLDER)
  12. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  13. # 封装数据库连接函数
  14. def get_db_connection():
  15. return sqlite3.connect('software_intro.db')
  16. # 初始化数据库表
  17. def init_db():
  18. conn = get_db_connection()
  19. cursor = conn.cursor()
  20. cursor.execute('''
  21. CREATE TABLE IF NOT EXISTS software_intro (
  22. id INTEGER PRIMARY KEY AUTOINCREMENT,
  23. title TEXT NOT NULL,
  24. intro TEXT
  25. )
  26. ''')
  27. conn.commit()
  28. conn.close()
  29. # 调用初始化函数
  30. init_db()
  31. # 获取软件介绍信息的路由
  32. @app.route('/software-intro/<int:id>', methods=['GET'])
  33. def get_software_intro(id):
  34. try:
  35. conn = get_db_connection()
  36. cursor = conn.cursor()
  37. cursor.execute('SELECT title, intro FROM software_intro WHERE id = ?',(id,))
  38. result = cursor.fetchone()
  39. conn.close()
  40. if result:
  41. title, intro = result
  42. return jsonify({
  43. 'title': title,
  44. 'intro': intro
  45. })
  46. return jsonify({}), 404
  47. except sqlite3.Error as e:
  48. print(f"数据库错误: {e}")
  49. return jsonify({"error": f"数据库错误: {str(e)}"}), 500
  50. # 更新软件介绍信息的路由
  51. @app.route('/software-intro/<int:id>', methods=['PUT'])
  52. def update_software_intro(id):
  53. try:
  54. data = request.get_json()
  55. title = data.get('title')
  56. intro = data.get('intro')
  57. conn = get_db_connection()
  58. cursor = conn.cursor()
  59. cursor.execute('UPDATE software_intro SET title =?, intro =? WHERE id = ?', (title, intro,id))
  60. conn.commit()
  61. conn.close()
  62. return jsonify({'message': '软件介绍更新成功'})
  63. except sqlite3.Error as e:
  64. print(f"数据库错误: {e}")
  65. return jsonify({"error": f"数据库错误: {str(e)}"}), 500
  66. # 处理图片上传的路由
  67. @app.route('/upload-image', methods=['POST'])
  68. def upload_image():
  69. file = request.files['image']
  70. if file:
  71. filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower()
  72. file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  73. imageUrl = f'http://127.0.0.1:5000/uploads/{filename}'
  74. return jsonify({'imageUrl': imageUrl})
  75. return jsonify({'error': '未找到图片文件'}), 400
  76. # 配置静态资源服务
  77. @app.route('/uploads/<path:filename>')
  78. def serve_image(filename):
  79. uploads_folder = os.path.join(app.root_path, 'uploads')
  80. return send_from_directory(uploads_folder, filename)
  81. if __name__ == '__main__':
  82. app.run(debug=True)