ball-tracking-cv/app/__init__.py
2025-08-10 10:01:43 +08:00

53 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging
import os
from flask import Flask, send_from_directory, send_file
from flask_cors import CORS
from .config import Config
from .logging_config import configure_logging
from .routes import bp as api_bp
def create_app(config_class: type[Config] = Config) -> Flask:
configure_logging()
# 设置静态文件目录
static_folder = os.path.join(os.path.dirname(__file__), 'web', 'dist')
app = Flask(__name__, static_folder=static_folder, static_url_path='')
app.config.from_object(config_class)
# CORS
CORS(app, resources={r"/api/*": {"origins": app.config.get("CORS_ORIGINS", "*")}})
# Blueprints
app.register_blueprint(api_bp)
# 静态文件路由
@app.route('/')
def serve_index():
"""服务主页面"""
return send_file(os.path.join(app.static_folder, 'index.html'))
@app.route('/<path:path>')
def serve_static(path):
"""服务其他静态文件"""
try:
return send_from_directory(app.static_folder, path)
except FileNotFoundError:
# 如果文件不存在返回主页面用于SPA路由
return send_file(os.path.join(app.static_folder, 'index.html'))
# Error handlers -> JSON
@app.errorhandler(413)
def too_large(_):
return {"success": False, "error": "上传文件过大"}, 413
@app.errorhandler(404)
def not_found(_):
return {"success": False, "error": "未找到"}, 404
@app.errorhandler(Exception)
def all_errors(e):
logging.getLogger(__name__).exception("Unhandled error")
return {"success": False, "error": str(e)}, 500
return app