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, )