我想指定一个棉花糖模式。对于我的一个字段,我希望对其进行验证,但它可以是字符串或字符串列表。我已经尝试过原始字段类型,但是它允许一切通过。有没有办法只验证我想要的两种类型?
就像是,
value = fields.Str() or fields.List()
最佳答案
我今天遇到了同样的问题,我想出了这个解决方案:
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()
您可以创建自定义字段并重载
_deserialize
方法,以便它验证代码 isinstance
所需的类型。我希望它对你有用。
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']}
关于Python Marshmallow Field 可以是两种不同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61614546/