from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.core.config import settings from app.api.v1.router import api_router @asynccontextmanager async def lifespan(app: FastAPI): """应用生命周期:启动时初始化连接,关闭时释放资源""" # 启动:验证数据库连接等 yield # 关闭:清理资源 app = FastAPI( title="Track Production API", description="工厂生产流转管理系统 API", version="0.1.0", lifespan=lifespan, ) # ---- CORS 跨域配置(从环境变量读取白名单) ---- app.add_middleware( CORSMiddleware, allow_origins=settings.CORS_ORIGINS_LIST, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ---- 注册路由 ---- app.include_router(api_router, prefix="/api/v1") @app.get("/health") async def health_check(): return {"status": "ok", "version": "0.1.0"}