"""FastAPI 应用工厂""" from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.api.lifespan import lifespan from app.api.routes import api_router from app.api.errors import proxy_pool_exception_handler, pydantic_validation_handler, general_exception_handler from app.core.exceptions import ProxyPoolException from pydantic import ValidationError from app.core.config import settings as app_settings # 导入并注册所有插件(显式注册模式) import app.plugins def create_app() -> FastAPI: app = FastAPI( title="代理池API", version="2.0.0", lifespan=lifespan, ) # CORS app.add_middleware( CORSMiddleware, allow_origins=app_settings.cors_origins_list, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 异常处理 app.add_exception_handler(ProxyPoolException, proxy_pool_exception_handler) app.add_exception_handler(ValidationError, pydantic_validation_handler) app.add_exception_handler(Exception, general_exception_handler) # 路由 app.include_router(api_router) @app.get("/") async def root(): return {"message": "欢迎使用代理池API", "status": "running", "data": None} @app.get("/health") async def health_check(): from datetime import datetime scheduler = app.state.scheduler_service return { "status": "healthy", "timestamp": datetime.now().isoformat(), "database": "connected", "scheduler": "running" if scheduler.running else "stopped", "version": "2.0.0", } return app