| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- """
- FastAPI应用入口 - 技术框架
- 增强功能:API接口日志记录,记录入参密文、入参明文、出参明文、出参密文
- """
- from fastapi import FastAPI, Request
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi.responses import JSONResponse
- from app.core.logger import setup_logger
- from app.utils.exceptions import BusinessException
- # 设置日志
- logger = setup_logger()
- # 创建FastAPI应用
- app = FastAPI(
- title="游铛铛客户端API",
- description="游铛铛产品客户端技术框架 - 增强API日志记录功能",
- version="1.0.0",
- docs_url="/docs",
- redoc_url="/redoc",
- )
- # CORS配置
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
- # 添加增强的API日志中间件(记录入参出参的明文和密文)
- from app.middleware.logging import APILoggingASGIMiddleware
- app.add_middleware(APILoggingASGIMiddleware)
- # 异常处理
- from fastapi import HTTPException
- @app.exception_handler(HTTPException)
- async def http_exception_handler(request: Request, exc: HTTPException):
- """统一处理HTTPException,返回前端期望的格式"""
- return JSONResponse(
- status_code=exc.status_code,
- content={"code": exc.status_code, "msg": exc.detail}
- )
- @app.exception_handler(BusinessException)
- async def business_exception_handler(request: Request, exc: BusinessException):
- return JSONResponse(
- status_code=200,
- content={"code": exc.code, "msg": exc.msg}
- )
- @app.exception_handler(Exception)
- async def general_exception_handler(request: Request, exc: Exception):
- logger.error("未处理的异常", exc_info=True)
- return JSONResponse(
- status_code=500,
- content={"code": 500, "msg": "服务器内部错误"}
- )
- @app.get("/")
- async def root():
- """根路径"""
- return {"message": "游铛铛客户端API", "version": "1.0.0"}
- @app.get("/health")
- async def health():
- """健康检查"""
- return {"status": "ok"}
- # 注册API路由
- from app.api import api_router
- app.include_router(api_router, prefix="/api")
- if __name__ == "__main__":
- import uvicorn
- uvicorn.run(app, host="0.0.0.0", port=9000)
|