50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
import logging
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from .api_response import error_response, exception_parts
|
|
from .config import get_settings
|
|
from .routers import admin, public, system
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
settings = get_settings()
|
|
logging.basicConfig(level=settings.log_level.upper())
|
|
|
|
app = FastAPI(title="WonderQ Admin API")
|
|
origins = ["*"] if settings.cors_origins == "*" else [item.strip() for item in settings.cors_origins.split(",") if item.strip()]
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(_request: Request, exc: RequestValidationError):
|
|
first = exc.errors()[0] if exc.errors() else {}
|
|
return error_response(
|
|
400,
|
|
str(first.get("msg", "请求参数不正确")),
|
|
error_code="VALIDATION_ERROR",
|
|
)
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(_request: Request, exc: HTTPException):
|
|
message, error_code, details = exception_parts(exc.detail)
|
|
return error_response(exc.status_code, message, error_code=error_code, details=details)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unhandled_exception_handler(request: Request, exc: Exception):
|
|
request.app.logger.exception(exc) if hasattr(request.app, "logger") else logging.exception(exc)
|
|
return error_response(500, "服务暂时不可用", error_code="INTERNAL_SERVER_ERROR")
|
|
|
|
app.include_router(public.router)
|
|
app.include_router(admin.router)
|
|
app.include_router(system.router)
|
|
return app
|
|
|
|
|
|
app = create_app()
|