I am verifying the data in the dictionary. I specify that the age field is of type int, but in practice, the age I pass in is of type str. Why is there no error?
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)
By default, marshmallow casts "12"
into an int
.
If you want to ensure it is an int
and not a string, use the strict
parameter.
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)