I have a marshmallow integer field, but very strange when I pass the data as {number:"123"} also works, as if was an integer, I would assume that internally is making the conversion to int, but don't want that I want to force the user to use INT all the time so there is no confusion of what data types can accept, is there a way or parameter for that?
number = fields.Integer(required=True,
validate=Range(min=1, error="Value must be greater than 0"))
thanks for the help guys.
Looking at the code I think it's not possible, and I'm surprised by that. I know there is a strict flag you can set, but it only operates in certain cases. Observe:
from marshmallow import *
from marshmallow.validate import Range
class MySchema(Schema):
number = fields.Integer(strict=True, required=True, validate=[Range(min=1, error="Value must be greater than 0")])
It works in this case:
s = MySchema()
s.dumps({'number': "123.1"})
>>> MarshalResult(data='{}', errors={'number': ['Not a valid integer.']})
But not in these case
s.dumps({'number': 123.1})
>>> MarshalResult(data='{"number": 123}', errors={})
s.dumps({'number': "123"})
>>> MarshalResult(data='{"number": 123}', errors={})
Which I find inconsistent. Perhaps your best bet is writing either a custom field or a different validator that validates the input before it's passed to your schema.
Update: Looks like the issue is fixed in recent versions of Marshmallow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With