feat: 添加自定义404和403错误响应,并优化图像服务接口逻辑

This commit is contained in:
晓丰 2025-06-06 23:00:23 +08:00
parent 101a819663
commit 12c66a9eb4

View File

@ -1,35 +1,35 @@
from flask import Flask, send_file, abort from flask import Flask, send_file, abort, request, jsonify
from pathlib import Path from pathlib import Path
app = Flask(__name__) app = Flask(__name__)
# 固定 screenshots 目录
PROJECT_ROOT = Path(__file__).parent.resolve() PROJECT_ROOT = Path(__file__).parent.resolve()
SCREENSHOTS_DIR = PROJECT_ROOT / "screenshots" SCREENSHOTS_DIR = PROJECT_ROOT / "screenshots"
@app.route('/image/<path:filename>') @app.route('/image/<path:filename>')
def serve_image(filename): def serve_image(filename):
app = Flask(__name__) file_path = SCREENSHOTS_DIR / filename
PROJECT_ROOT = Path(__file__).parent.resolve() # 防止路径越界访问
SCREENSHOTS_DIR = PROJECT_ROOT / "screenshots" try:
file_path.resolve().relative_to(SCREENSHOTS_DIR.resolve())
except ValueError:
abort(403, description=f"禁止访问目录外文件: {file_path.resolve()}")
@app.route('/image/<path:filename>') if not file_path.exists():
def serve_image(filename): abort(404, description=f"文件不存在: {file_path.resolve()}")
file_path = SCREENSHOTS_DIR / filename
# 防止路径越界访问 return send_file(file_path, as_attachment=False)
try:
file_path.resolve().relative_to(SCREENSHOTS_DIR.resolve())
except ValueError:
abort(403, description=f"禁止访问目录外文件: {file_path.resolve()}")
if not file_path.exists(): # 自定义 404 错误响应
abort(404, description=f"文件不存在: {file_path.resolve()}") @app.errorhandler(404)
def handle_404(e):
return send_file(file_path, as_attachment=False) return f"404 错误:{e.description}", 404
# 自定义 403 错误响应
@app.errorhandler(403)
def handle_403(e):
return f"403 错误:{e.description}", 403
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5000) app.run(host='0.0.0.0', debug=False, port=5000)