【问题标题】:Python Marshmallow Field can be two different typesPython Marshmallow Field 可以是两种不同的类型
【发布时间】:2020-05-05 13:38:34
【问题描述】:

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

类似的,

value = fields.Str() or fields.List()

【问题讨论】:

标签: python marshmallow


【解决方案1】:

我今天遇到了同样的问题,我想出了这个解决方案:

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']}

【讨论】:

  • 很好的解决方法,如果我们有类似“oneof”字段的东西,我会很棒。
【解决方案2】:

Mapping(s) 的解决方案,与上述类似:

from typing import List, Mapping, Any
from marshmallow import Schema, fields
from marshmallow.exceptions import ValidationError


class UnionField(fields.Field):
    """Field that deserializes multi-type input data to app-level objects."""

    def __init__(self, val_types: List[fields.Field]):
        self.valid_types = val_types
        super().__init__()

    def _deserialize(
        self, value: Any, attr: str = None, data: Mapping[str, Any] = None, **kwargs
    ):
        """
        _deserialize defines a custom Marshmallow Schema Field that takes in mutli-type input data to
        app-level objects.
        
        Parameters
        ----------
        value : {Any}
            The value to be deserialized.
        
        Keyword Parameters
        ----------
        attr : {str} [Optional]
            The attribute/key in data to be deserialized. (default: {None})
        data : {Optional[Mapping[str, Any]]}
            The raw input data passed to the Schema.load. (default: {None})
        
        Raises
        ----------
        ValidationError : Exception
            Raised when the validation fails on a field or schema.
        """
        errors = []
        # iterate through the types being passed into UnionField via val_types
        for field in self.valid_types:
            try:
                # inherit deserialize method from Fields class
                return field.deserialize(value, attr, data, **kwargs)
            # if error, add error message to error list
            except ValidationError as error:
                errors.append(error.messages)
                raise ValidationError(errors)

用途:

class SampleSchema(Schema):
    ex_attr = fields.Dict(keys=fields.Str(), values=UnionField([fields.Str(), fields.Number()]))

学分:安娜·K

【讨论】:

  • raise ValidationError(errors) 必须在循环之外
【解决方案3】:

marshmallow-oneofschema 项目在这里有一个很好的解决方案。
https://github.com/marshmallow-code/marshmallow-oneofschema

来自他们的示例代码:

import marshmallow
import marshmallow.fields
from marshmallow_oneofschema import OneOfSchema


class Foo:
    def __init__(self, foo):
        self.foo = foo


class Bar:
    def __init__(self, bar):
        self.bar = bar


class FooSchema(marshmallow.Schema):
    foo = marshmallow.fields.String(required=True)

    @marshmallow.post_load
    def make_foo(self, data, **kwargs):
        return Foo(**data)


class BarSchema(marshmallow.Schema):
    bar = marshmallow.fields.Integer(required=True)

    @marshmallow.post_load
    def make_bar(self, data, **kwargs):
        return Bar(**data)


class MyUberSchema(OneOfSchema):
    type_schemas = {"foo": FooSchema, "bar": BarSchema}

    def get_obj_type(self, obj):
        if isinstance(obj, Foo):
            return "foo"
        elif isinstance(obj, Bar):
            return "bar"
        else:
            raise Exception("Unknown object type: {}".format(obj.__class__.__name__))


MyUberSchema().dump([Foo(foo="hello"), Bar(bar=123)], many=True)
# => [{'type': 'foo', 'foo': 'hello'}, {'type': 'bar', 'bar': 123}]

MyUberSchema().load(
    [{"type": "foo", "foo": "hello"}, {"type": "bar", "bar": 123}], many=True
)
# => [Foo('hello'), Bar(123)]

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多