字段类型是int的时候传入str没有报错?

There is no error when str is passed in when the field type is int?

我正在验证字典中的数据。我指定年龄字段是int类型,但实际上,我传入的年龄是str类型。为什么没有报错?


from marshmallow import Schema, fields


class UserSchema(Schema):
    name = fields.Str()
    age = fields.Int()


user_data = {
    "name": "Ken",
    "age": "12"
}

try:
    UserSchema().load(user_data)
except Exception as e:
    print(e)

我猜想 marshmallow.fields 在某些时候隐式地将 age 解析为 int 并且它没有抛出任何异常,因为“12”可以很好地转换为 12。当我运行 你的代码就是这样,name 是 "Ken" 而 age 是 12。如果我将“12”更改为“12a”,那么它 returns 如您所料的异常。

默认情况下,marshmallow 将 "12" 转换为 int

如果要确保它是 int 而不是字符串,请使用 strict 参数。

https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.fields.Integer

strict – If True, only integer types are valid. Otherwise, any value castable to int is valid.

class UserSchema(Schema):
    name = fields.Str()
    age = fields.Int(strict=True)