file_route.py 915 B

123456789101112131415161718192021222324252627282930313233343536
  1. import os
  2. from flask import abort, send_from_directory, current_app, jsonify
  3. from app.routes import file_routes
  4. STATIC_FOLDER = os.path.join(os.getcwd(), 'app', 'static')
  5. @file_routes.route('/static/<path:filepath>')
  6. def serve_static(filepath):
  7. """
  8. 自定义路由处理 static 路径下的所有静态文件请求(绕过 Flask 默认 static 机制)
  9. """
  10. # 安全性检查
  11. if '..' in filepath or filepath.startswith('/'):
  12. abort(400)
  13. abs_path = os.path.join(STATIC_FOLDER, filepath)
  14. if not os.path.isfile(abs_path):
  15. abort(404)
  16. current_app.logger.info(f'Serving static file: {abs_path}')
  17. return send_from_directory(STATIC_FOLDER, filepath)
  18. @file_routes.route('/static')
  19. def static():
  20. """
  21. 静态文件路由
  22. """
  23. current_app.logger.info(f'Serving static file')
  24. return jsonify({
  25. 'operation': 'Serving static file',
  26. }), 201