0

I'm building a simple JSON API using Flask and wtforms-json. I have a problem where fields are allowed to be None, even when they really should not be, for example something this:

wtforms.BooleanField('state', validators=[validators.Optional(), validators.AnyOf([True, False])])

still lets through explicit None (or null) values somehow instead of failing validation or removing the field from the form's patch_data() alltogether (although None sometimes should be valid). Same with String fields, setting a default value doesn't help either.

I've written a small test script to illustrate the problem. Setting name to '' results in it being None in the patch data instead of being missing like the second accepted variable.

json {}
errors {}
form.data {'name': None, 'potato': None}
form.patch_data {}

json {'name': ''}
errors {}
form.data {'name': None, 'potato': None}
form.patch_data {'name': None}

json {'name': 'a'}
errors {'name': ['Field must be between 2 and 128 characters long.']}
form.data {'name': 'a', 'potato': None}
form.patch_data {'name': 'a'}

json {'name': 'ab'}
errors {}
form.data {'name': 'ab', 'potato': None}
form.patch_data {'name': 'ab'}

json {'potato': None}
errors {}
form.data {'name': None, 'potato': None}
form.patch_data {'potato': None}

json {'potato': ''}
errors {}
form.data {'name': None, 'potato': None}
form.patch_data {'potato': None}

json {'potato': 'minimum'}
errors {'potato': ['Invalid value, must be one of: maximum.']}
form.data {'name': None, 'potato': 'minimum'}
form.patch_data {'potato': 'minimum'}

json {'potato': 'maximum'}
errors {}
form.data {'name': None, 'potato': 'maximum'}
form.patch_data {'potato': 'maximum'}
kshade
  • 21
  • 5
  • Wait, if it's optional, then how come the empty string is not allowed? That's the point of optional. – Luis Orduz Oct 20 '17 at 20:42
  • In normal wtforms, yes, but wtforms-json adds the patch_data() function which is meant to filter out missing fields while still allowing None/null to be explicitly sent if allowed. '' also should not magically become None. See https://wtforms-json.readthedocs.io/en/latest/#using-patch-data – kshade Oct 20 '17 at 20:45

0 Answers0