24

是否可以使用棉花糖验证列表?

class SimpleListInput(Schema):
    items = fields.List(fields.String(), required=True)

# expected invalid type error
data, errors = SimpleListInput().load({'some': 'value'})

# should be ok 
data, errors = SimpleListInput().load(['some', 'value'])

或者预计只验证对象?

4

3 回答 3

33

要验证顶级列表,您需要使用many=True参数实例化列表项架构。

例子:

class UserSchema(marshmallow.Schema):
    name = marshmallow.fields.String()

data, errors = UserSchema(many=True).load([
    {'name': 'John Doe'},
    {'name': 'Jane Doe'}
])

但它仍然需要是对象模式,Marshmallow 不支持使用顶级非对象列表。如果您需要验证非对象类型的顶级列表,一种解决方法是使用您的类型的一个 List 字段定义一个模式,并将有效负载视为对象:

class SimpleListInput(marshmallow.Schema):
    items = marshmallow.fields.List(marshmallow.fields.String(), required=True)

payload = ['foo', 'bar']
data, errors = SimpleListInput().load({'items': payload})
于 2016-12-01T00:23:46.737 回答
13

SimpleListInput 是一个具有“项目”属性的类。属性“items”是接受字符串列表的人。

>>> data, errors = SimpleListInput().load({'items':['some', 'value']})
>>> print data, errors
{'items': [u'some', u'value']} 
{}
>>> data, errors = SimpleListInput().load({'items':[]})
>>> print data, errors
{'items': []} 
{}
>>> data, errors = SimpleListInput().load({})
>>> print data, errors
{} 
{'items': [u'Missing data for required field.']}

例如,如果您想要自定义验证,则不接受“项目”中的空列表:

from marshmallow import fields, Schema, validates, ValidationError

class SimpleListInput(Schema):
    items = fields.List(fields.String(), required=True)

    @validates('items')
    def validate_length(self, value):
        if len(value) < 1:
            raise ValidationError('Quantity must be greater than 0.') 

然后...

>>> data, errors = SimpleListInput().load({'items':[]})
>>> print data, errors
{'items': []} 
{'items': ['Quantity must be greater than 0.']}

看看验证

更新:

正如@Turn 在下面评论的那样。你可以这样做:

from marshmallow import fields, Schema, validate

class SimpleListInput(Schema):        
    items = fields.List(fields.String(), required=True, validate=validate.Length(min=1))
于 2016-09-29T01:48:07.943 回答
4

请看一下我编写的一个小库,它试图解决这个问题:https ://github.com/and-semakin/marshmallow-toplevel 。

安装:

pip install marshmallow-toplevel

用法(来自Maxim Kulkin的示例):

import marshmallow
from marshmallow_toplevel import TopLevelSchema

class SimpleListInput(TopLevelSchema):
    _toplevel = marshmallow.fields.List(
        marshmallow.fields.String(),
        required=True,
        validate=marshmallow.validate.Length(1, 10)
    )

# raises ValidationError, because:
# Length must be between 1 and 10.
SimpleListInput().load([])

# raises ValidationError, because:
# Length must be between 1 and 10.
SimpleListInput().load(["qwe" for _ in range(11)])

# successfully loads data
payload = ["foo", "bar"]
data = SimpleListInput().load(payload)
assert data == ["foo", "bar"]

当然,它可以与更复杂的模式一起使用,而不仅仅是示例中的字符串。

于 2019-12-25T09:51:00.987 回答