api/app/main.py
2025-04-09 21:45:42 +08:00

77 lines
2.2 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.

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.exceptions import add_exception_handlers
from app.core.middleware import add_response_middleware
from app.schemas.response import StandardResponse
from starlette.middleware.sessions import SessionMiddleware
# 配置日志
logging.basicConfig(
level=logging.DEBUG, # 设置为DEBUG级别以显示更多日志
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,
openapi_url=f"{settings.API_V1_STR}/openapi.json"
)
logger.info("开始配置应用中间件和路由...")
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=settings.BACKEND_CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
logger.info("CORS中间件已添加")
# 添加Session中间件
app.add_middleware(
SessionMiddleware,
secret_key=settings.SECRET_KEY,
session_cookie="session",
max_age=1800 # 30分钟
)
# 添加异常处理器
add_exception_handlers(app)
logger.info("异常处理器已添加")
# add_response_middleware(app)
# logger.info("响应中间件已添加")
# 包含API路由
app.include_router(api_router, prefix=settings.API_V1_STR)
logger.info(f"API路由已添加前缀: {settings.API_V1_STR}")
@app.get("/")
async def root():
logger.info("访问根路径")
return StandardResponse(code=200, data={"message": "欢迎使用美搭Meida API服务"})
@app.get("/health")
async def health_check():
logger.debug("健康检查")
return StandardResponse(code=200, data={"status": "healthy"})