dingdanquanliucheng/backend/app/main.py

49 lines
1.4 KiB
Python
Raw Normal View History

"""FastAPI 应用入口。
创建应用实例配置 CORS 中间件注册全局异常处理器挂载 API 路由
启动命令: uvicorn backend.app.main:app --reload
"""
2026-05-14 10:15:51 +08:00
from fastapi import FastAPI
2026-05-14 13:51:06 +08:00
from fastapi import Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
2026-05-14 10:15:51 +08:00
2026-05-14 13:51:06 +08:00
from backend.app.api.router import api_router
from backend.app.core.config import get_settings
from backend.app.core.exceptions import AppException
2026-05-14 10:15:51 +08:00
2026-05-14 13:51:06 +08:00
settings = get_settings()
2026-05-14 10:15:51 +08:00
2026-05-14 13:51:06 +08:00
app = FastAPI(title=settings.app_name)
2026-05-14 10:15:51 +08:00
# 配置 CORS 跨域,允许前端开发服务器访问
2026-05-14 13:51:06 +08:00
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
2026-05-14 10:15:51 +08:00
2026-05-14 13:51:06 +08:00
@app.exception_handler(AppException)
async def app_exception_handler(_: Request, exc: AppException) -> JSONResponse:
"""全局捕获 AppException返回统一的错误 JSON 格式。
避免每个路由重复构造错误响应所有业务异常由此处理器统一格式化
"""
2026-05-14 13:51:06 +08:00
# 统一业务异常返回格式,避免每个接口重复构造错误响应。
return JSONResponse(
status_code=exc.status_code,
content={
"code": exc.code,
"message": exc.message,
"data": {},
},
)
2026-05-14 10:15:51 +08:00
2026-05-14 13:51:06 +08:00
# 挂载所有 API 路由,路由前缀在 router.py 中统一定义
2026-05-14 13:51:06 +08:00
app.include_router(api_router)