Costum方案不能验证FASTAPI数据



在自定义方案中,我将价格字段定义为一个数字,但在那里传递了一个字符串,该方案没有以任何方式进行验证,也没有抛出错误。如果不采用皮丹蒂克模型,如何改变这种行为?

代码:

def magic_data_reader(raw_body: bytes):
raw_body = dict(eval(raw_body))
return {
"size": len(raw_body),
"content": {
"name": raw_body['name'],
"price": raw_body['price'],
"description": raw_body['description'],
},
}

@router.post(
"/items/",
openapi_extra={
"requestBody": {
"content": {
"application/json": {
"schema": {
"required": ["name", "price"],
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"description": {"type": "string"},
},
}
}
},
"required": True,
},
},
)
async def create_item(request: Request):
raw_body = await request.body()
data = magic_data_reader(raw_body)
return data

请求:

{
"name": "Jack",
"price": "dddd",
"description": "Something"
}

响应主体:

{
"size": 3,
"content": {
"name": "Jack",
"price": "dddd",
"description": "Something"
}
}

openapi_extra参数只是向OpenAPI文档添加信息,它不生成任何验证逻辑。如文档中所述,这是一个功能,例如,如果您想编写自己的自定义验证逻辑:

例如,您可以决定用自己的代码读取和验证请求,而不使用Pydantic的FastAPI的自动功能,但您仍然可以在OpenAPI模式中定义请求。

要获得FastAPI自动验证的优势,必须使用Pydantic模型。

最新更新