【问题标题】:How to disable schema checking in FastAPI?如何在 FastAPI 中禁用模式检查?
【发布时间】:2021-04-18 22:36:43
【问题描述】:

我正在将服务从 Flask 迁移到 FastAPI,并使用 Pydantic 模型生成文档。但是,我对架构检查有点不确定。恐怕会有一些意想不到的数据(比如不同的字段格式),它会返回错误。

在 Pydantic 文档中,有一些方法可以在不检查架构的情况下创建模型:https://pydantic-docs.helpmanual.io/usage/models/#creating-models-without-validation

但是,由于这显然是由 FastAPI 本身实例化的,我不知道如何在从 FastAPI 返回时禁用此架构检查。

【问题讨论】:

    标签: python validation schema fastapi pydantic


    【解决方案1】:

    您可以返回Response directly,或使用custom responses 进行自动转换。在这种情况下,不会根据响应模型验证响应数据。但是您仍然可以按照Additional Responses in OpenAPI 中的说明记录它。

    例子:

    class SomeModel(BaseModel):
        num: int
    
    
    @app.get("/get", response_model=SomeModel)
    def handler(param: int):
        if param == 1:  # ok
            return {"num": "1"}
        elif param == 2:  # validation error
            return {"num": "not a number"}
        elif param == 3:  # ok (return without validation)
            return JSONResponse(content={"num": "not a number"})
        elif param == 4:  # ok (return without validation and conversion)
            return Response(content=json.dumps({"num": "not a number"}), media_type="application/json")
    

    【讨论】:

    • 您也可以使用Any 类型。请参阅下面的答案。
    【解决方案2】:

    FastAPI 不强制执行任何类型的验证,因此如果您不想要它,请不要使用 Pydantic 模型或类型提示。

    app.get('/')
    async def your_function(input_param):
      return { 'param': input_param }
    
    # Don't use models or type hints when defining the function params.
    # `input_param` can be anything, no validation will be performed.
    

    但是,正如@Tryph 正确指出的那样,由于您使用 Pydantic 来生成文档,因此您可以像这样简单地使用 Any 类型:

    from typing import Any
    from pydantic import BaseModel
    
    class YourClass(BaseModel):
        any_value: Any
    

    请注意Any 类型也接受None,实际上该字段是可选的。 (另请参阅 Pydantic 中的 typing.Any docs

    【讨论】:

    • pydantic 模型也用于生成文档。
    【解决方案3】:

    您可以将请求模型设置为typing.Dicttyping.List

    from typing import Dict
    
    app.post('/')
    async def your_function(body: Dict):
      return { 'request_body': body}
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 2020-01-12
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多