I want to specify a marshmallow schema. For one of my fields, I want it to be validated however it can be EITHER a string or a list of strings. I have tried the Raw field type however that is allows everything through. Is there a way to just validate the two types that I want?
Something like,
value = fields.Str() or fields.List()
I had the same issue today, and I came up with this solution:
class ValueField(fields.Field):
def _deserialize(self, value, attr, data, **kwargs):
if isinstance(value, str) or isinstance(value, list):
return value
else:
raise ValidationError('Field should be str or list')
class Foo(Schema):
value = ValueField()
other_field = fields.Integer()
You can create a custom field and overload the _deserialize method so that it validates if the code isinstance of desired types.
I hope it'll work for you.
foo.load({'value': 'asdf', 'other_field': 1})
>>> {'other_field': 1, 'value': 'asdf'}
foo.load({'value': ['asdf'], 'other_field': 1})
>>> {'other_field': 1, 'value': ['asdf']}
foo.load({'value': 1, 'other_field': 1})
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 723, in load
data, many=many, partial=partial, unknown=unknown, postprocess=True
File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 904, in _do_load
raise exc
marshmallow.exceptions.ValidationError: {'value': ['Field should be str or list']}
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