Files
ocean_project_manager/backend/main.py
T
xsl 64b08c4e67 [backend] fix: 修复认证相关的测试
- 修改LoginRequest schema,使字段为可选
- 添加自定义异常处理器以返回正确的JSON格式
- 修改认证中间件,返回正确的错误码和响应格式
- 所有auth测试(10个)全部通过

测试结果:10 passed
2026-01-26 10:13:09 +08:00

92 lines
2.2 KiB
Python

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import HTTPException, RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from config.settings import get_settings
from config.database import init_db
from src.routes import auth_router, users_router, projects_router
settings = get_settings()
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
description="海洋项目管理系统后端API",
docs_url="/docs",
redoc_url="/redoc",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth_router, prefix="/api/v1")
app.include_router(users_router, prefix="/api/v1")
app.include_router(projects_router, prefix="/api/v1")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
if isinstance(exc.detail, dict):
return JSONResponse(
status_code=exc.status_code,
content=exc.detail,
)
return JSONResponse(
status_code=exc.status_code,
content={
"success": False,
"message": exc.detail,
"data": None,
"error_code": None,
},
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={
"success": False,
"message": "请求验证失败",
"data": exc.errors(),
"error_code": "1001",
},
)
@app.on_event("startup")
async def startup_event():
await init_db()
@app.get("/")
async def root():
return {
"app": settings.APP_NAME,
"version": settings.APP_VERSION,
"status": "running",
}
@app.get("/health")
async def health():
return {"status": "healthy"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=5000,
reload=settings.DEBUG,
)