在 pydantic 中验证

Validation in pydantic

我为我的数据解析编写了一些 classes。数据是具有很大深度的字典,很多字符串值(数字、日期、布尔值)都是字符串。对于显示的数据,没有问题,并且类型转换效果很好。但是对于“空”值(“”值),我得到验证错误。我试图编写验证器但没有成功。我应该如何意识到这一点?

class Amount(BaseModel):

    amt: float = 0
    cur: int = 0

    @validator("amt", "cur")
    def check_str(cls, x):
        if x == "": 
            return 0
        else: 
            return x

d = Amount.parse_obj({"amt": "", "cur": ""})
2 validation errors for Amount
amt
  value is not a valid float (type=type_error.float)
cur
  value is not a valid integer (type=type_error.integer)

P.S。在主体中写 try-except 构造是没有用的,因为 Amount class 只是一个小子 class 更大的构造

您需要将 pre=True 添加到您的验证器:

class Amount(BaseModel):

    amt: float = 0
    cur: int = 0

    @validator("amt", "cur", pre=True)
    def check_str(cls, x):
        if x == "": 
            return 0
        else: 
            return x

d = Amount.parse_obj({"amt": "", "cur": ""})

参考资料

https://pydantic-docs.helpmanual.io/usage/validators/#pre-and-per-item-validators