From d5d7f9b89a54c01640099f985250157394625668 Mon Sep 17 00:00:00 2001 From: aaron <> Date: Wed, 9 Apr 2025 13:50:39 +0800 Subject: [PATCH] update --- app/main.py | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index 702357a..01f5c93 100644 --- a/app/main.py +++ b/app/main.py @@ -1,4 +1,49 @@ -# 从项目根目录导入应用实例 -from main import app +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from contextlib import asynccontextmanager +from app.core.config import settings +from app.api.v1.api import api_router +from app.core.middleware import add_response_middleware +from app.core.exceptions import add_exception_handlers -# 使用uvicorn app.main:app启动时会使用这个导入的app实例 \ No newline at end of file +@asynccontextmanager +async def lifespan(app: FastAPI): + # 在应用启动时执行 + from app.db.init_db import init_db + await init_db() + yield + # 在应用关闭时执行 + # 清理代码可以放在这里 + +app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.PROJECT_VERSION, + lifespan=lifespan +) + +# 配置CORS +app.add_middleware( + CORSMiddleware, + allow_origins=settings.BACKEND_CORS_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# 添加响应中间件 +add_response_middleware(app) + +# 添加异常处理器 +add_exception_handlers(app) + +# 包含API路由 +app.include_router(api_router, prefix=settings.API_V1_STR) + +@app.get("/") +async def root(): + return {"message": "欢迎使用美搭Meida API服务"} + +@app.get("/health") +async def health_check(): + return {"status": "healthy"} \ No newline at end of file