Add FastAPI admin/public API service, database setup, Docker deployment files, docs, and tests.
44 lines
1.7 KiB
Python
44 lines
1.7 KiB
Python
import logging
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from .config import get_settings
|
|
from .routers import admin, public
|
|
|
|
|
|
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 JSONResponse(status_code=400, content={"message": first.get("msg", "请求参数不正确")})
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(_request: Request, exc: HTTPException):
|
|
return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
|
|
|
|
@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 JSONResponse(status_code=500, content={"message": "服务暂时不可用"})
|
|
|
|
app.include_router(public.router)
|
|
app.include_router(admin.router)
|
|
return app
|
|
|
|
|
|
app = create_app()
|