Python Marshmallow Field 可以是两种不同的类型

标签 python marshmallow

我想指定一个棉花糖模式。对于我的一个字段,我希望对其进行验证,但它可以是字符串或字符串列表。我已经尝试过原始字段类型,但是它允许一切通过。有没有办法只验证我想要的两种类型?

就像是,

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/

相关文章:

python - Pylons FormEncode 带有表单元素数组

python csv复制列

Python 对 float 取模

python - 在 Marshallow/SQLAlchemy 架构上展平数据

python - 使用棉花糖验证具有列表长度约束的模式列表

python - 将数字列表返回到字符串列表

python - 反序列化棉花糖中的嵌套字段

python - 是否可以在棉花糖中定义具有互斥字段的嵌套模式?

python-3.x - 如何在棉花糖模式中添加多个验证参数

python - 当我给出一个包含两个不同形状的 ndarray 的列表时,np.array() 不起作用