Але*_*ндр 14 python pydantic fastapi
我有 2 个 Pydantic 型号 (var1和var2)。该方法的输入PostExample可以接收第一模型或第二模型的数据。使用Union有助于解决此问题,但在验证过程中,它会引发第一个模型和第二个模型的错误。
如何做到在填写字段时出现错误时,仅针对某个模型返回验证器错误,而不是同时返回两个模型?(如果有帮助的话,可以通过字段A的长度来区分模型)。
主要.py
@app.post("/PostExample")
def postExample(request: Union[schemas.var1, schemas.var2]):
result = post_registration_request.requsest_response()
return result
Run Code Online (Sandbox Code Playgroud)
模式.py
class var1(BaseModel):
A: str
B: int
C: str
D: str
class var2(BaseModel):
A: str
E: int
F: str
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 16
您可以使用受歧视的工会(感谢 @larsks 在评论中提到这一点)。设置一个可区分的联合,“验证速度更快,因为它仅针对一种模型进行尝试”,并且“在失败的情况下仅引发一个显式错误”。下面给出工作示例。
另一种方法是尝试解析模型(基于您作为查询/路径参数传递的鉴别器),如本答案 (选项 1)中所述。
应用程序.py
import schemas
from fastapi import FastAPI, Body
from typing import Union
app = FastAPI()
@app.post("/")
def submit(item: Union[schemas.Model1, schemas.Model2] = Body(..., discriminator='model_type')):
return item
Run Code Online (Sandbox Code Playgroud)
模式.py
from typing import Literal
from pydantic import BaseModel
class Model1(BaseModel):
model_type: Literal['m1']
A: str
B: int
C: str
D: str
class Model2(BaseModel):
model_type: Literal['m2']
A: str
E: int
F: str
Run Code Online (Sandbox Code Playgroud)
测试输入 - 输出
#1 Successful Response #2 Validation error #3 Validation error
# Request body # Request body # Request body
{ { {
"model_type": "m1", "model_type": "m1", "model_type": "m2",
"A": "string", "A": "string", "A": "string",
"B": 0, "C": "string", "C": "string",
"C": "string", "D": "string" "D": "string"
"D": "string" } }
}
# Server response # Server response # Server response
200 { {
"detail": [ "detail": [
{ {
"loc": [ "loc": [
"body", "body",
"Model1", "Model2",
"B" "E"
], ],
"msg": "field required", "msg": "field required",
"type": "value_error.missing" "type": "value_error.missing"
} },
] {
} "loc": [
"body",
"Model2",
"F"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17325 次 |
| 最近记录: |