【问题标题】:How to disable schema checking in FastAPI?如何在 FastAPI 中禁用模式检查?
【发布时间】:2021-04-18 22:36:43
【问题描述】:
【问题讨论】:
标签:
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")
【解决方案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)
【解决方案3】:
您可以将请求模型设置为typing.Dict 或typing.List
from typing import Dict
app.post('/')
async def your_function(body: Dict):
return { 'request_body': body}