""" FastAPI应用主入口 """ import logging from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.trustedhost import TrustedHostMiddleware from fastapi.responses import JSONResponse from loguru import logger from app.api.v1.api import api_router from app.config import settings from app.database import close_db, init_db from app.utils.logger import setup_logger @asynccontextmanager async def lifespan(app: FastAPI): """ 应用生命周期管理 """ # 启动时执行 logger.info("Starting up...") try: await init_db() logger.info("Database initialized") except Exception as e: logger.warning(f"Database initialization failed: {e}") logger.warning("Continuing without database connection...") yield # 关闭时执行 logger.info("Shutting down...") try: await close_db() logger.info("Database connections closed") except Exception as e: logger.warning(f"Database close failed: {e}") # 创建FastAPI应用实例 app = FastAPI( title=settings.APP_NAME, version=settings.APP_VERSION, description="税务风控审查系统后端API", openapi_url=f"{settings.API_V1_STR}/openapi.json", docs_url=f"{settings.API_V1_STR}/docs", redoc_url=f"{settings.API_V1_STR}/redoc", lifespan=lifespan, ) # 添加中间件 # 信任的主机 app.add_middleware( TrustedHostMiddleware, allowed_hosts=["*"], # allowed_hosts=["*"] if settings.DEBUG else ["localhost", "127.0.0.1"], ) # CORS中间件 - 支持多环境 # 开发环境:允许所有来源 cors_origins = ["*"] # 生产环境:通过nginx访问,使用nginx代理的域名 # cors_origins = ["*"] if settings.DEBUG else [ # "http://localhost", # "http://127.0.0.1", # "http://localhost:80", # "http://127.0.0.1:80", # ] app.add_middleware( CORSMiddleware, allow_origins=cors_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 包含API路由 app.include_router(api_router, prefix=settings.API_V1_STR) @app.get("/") async def root(): """ 根路径 """ return { "message": "Welcome to DeepRisk Backend", "version": settings.APP_VERSION, "docs": f"{settings.API_V1_STR}/docs", } @app.get("/health") async def health_check(): """ 健康检查端点 """ return {"status": "healthy", "version": settings.APP_VERSION} @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): """ 全局异常处理器 """ logger.exception("Unhandled exception", exc_info=exc) return JSONResponse( status_code=500, content={ "error": { "code": "INTERNAL_SERVER_ERROR", "message": "An internal server error occurred", } }, ) if __name__ == "__main__": import uvicorn # 配置日志 setup_logger() # 运行应用 uvicorn.run( "app.main:app", host="0.0.0.0", port=8000, reload=settings.DEBUG, log_level=settings.LOG_LEVEL.lower(), )