59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from contextlib import asynccontextmanager
|
|
import logging
|
|
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
|
|
|
|
# 配置日志
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
# 在应用启动时执行
|
|
logger.info("应用启动,初始化数据库...")
|
|
from app.db.init_db import init_db
|
|
await init_db()
|
|
logger.info("数据库初始化完成")
|
|
yield
|
|
# 在应用关闭时执行
|
|
logger.info("应用关闭")
|
|
|
|
app = FastAPI(
|
|
title=settings.PROJECT_NAME,
|
|
description=settings.PROJECT_DESCRIPTION,
|
|
version=settings.PROJECT_VERSION,
|
|
lifespan=lifespan
|
|
)
|
|
|
|
# 配置CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.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"} |