【问题标题】:How to use logging in pydantic/fast API如何在 pydantic/fast API 中使用日志记录
【发布时间】:2020-10-06 12:57:59
【问题描述】:

我正在使用快速 API 来创建 API,并希望使用日志记录来创建 csv 日志。 API 代码如下所示:

@app.post("/path")
async def return_something(header: header, body: body):
    ...
    logger.info('....')
    return something

Pydantic 模型的定义如下:

class header(BaseModel):
    field1: str
    field2: list

我正在使用这样的记录器

from logger import ApplicationLogger
logger = ApplicationLogger()

问题是如何使用现有的渴望来记录 pydantic 错误以进行现场验证?

【问题讨论】:

    标签: python logging fastapi pydantic


    【解决方案1】:

    根据您的用例,您可以使用以下实现。两者都实现了一个中间件exception_handler,以捕获 ValidationErrorRequestValidationError。您可以在中间件中记录您需要的任何内容,如下所述。有关更多信息,您可以查看这些 Github 问题(https://github.com/tiangolo/fastapi/issues/1486https://github.com/tiangolo/fastapi/pull/853

    app = FastAPI()
    
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request, exc: Exception):
        """LOG HERE"""
        return PlainTextResponse(str(exc), status_code=400)
    

    app = FastAPI()
    
    async def http422_error_handler(
        _: Request, exc: Union[RequestValidationError, ValidationError]) -> JSONResponse:
        """LOG HERE"""
        return JSONResponse(
            {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY
        )
    
    app.add_exception_handler(ValidationError, http422_error_handler)
    app.add_exception_handler(RequestValidationError, http422_error_handler)
    

    【讨论】:

      【解决方案2】:

      如果验证不正确,Pydantic 会自动将错误记录到您的终端。

      您也可以像这样记录架构:

      logger.info(f"header schema: {header}")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 2015-02-19
        相关资源
        最近更新 更多