Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python marshmallow force field.int to only accept int and not strings

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.

like image 817
pelos Avatar asked Dec 14 '22 16:12

pelos


1 Answers

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

like image 188
PoP Avatar answered Dec 29 '22 10:12

PoP