37 lines
952 B
Python
37 lines
952 B
Python
from fastapi import FastAPI
|
|
from fastapi import Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from backend.app.api.router import api_router
|
|
from backend.app.core.config import get_settings
|
|
from backend.app.core.exceptions import AppException
|
|
|
|
settings = get_settings()
|
|
|
|
app = FastAPI(title=settings.app_name)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.exception_handler(AppException)
|
|
async def app_exception_handler(_: Request, exc: AppException) -> JSONResponse:
|
|
# 统一业务异常返回格式,避免每个接口重复构造错误响应。
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={
|
|
"code": exc.code,
|
|
"message": exc.message,
|
|
"data": {},
|
|
},
|
|
)
|
|
|
|
|
|
app.include_router(api_router)
|