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

时间:2016-05-15 10:50:40

标签: python marshmallow

是否可以使用marshmallow验证列表?

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

或者预计仅验证对象?

3 个答案:

答案 0 :(得分:13)

要验证顶级列表,您需要使用function initPano() { // Set up Street View and initially set it visible. Register the // custom panorama provider function. Set the StreetView to display // the custom panorama 'reception' which we check for below. var panorama = new google.maps.StreetViewPanorama( document.getElementById('map'), { pano: 'reception', visible: true, panoProvider: getCustomPanorama } ); } // Return a pano image given the panoID. function getCustomPanoramaTileUrl(pano, zoom, tileX, tileY) { // Note: robust custom panorama methods would require tiled pano data. // Here we're just using a single tile, set to the tile size and equal // to the pano "world" size. return 'img/pano-1.jpg'; // <----------- HERE } // Construct the appropriate StreetViewPanoramaData given // the passed pano IDs. function getCustomPanorama(pano, zoom, tileX, tileY) { if(pano === 'reception') { return { location: { pano: 'reception', description: 'Description' }, links: [], // The text for the copyright control. copyright: 'Imagery (c) 2010 Google', // The definition of the tiles for this panorama. tiles: { tileSize: new google.maps.Size(1024, 512), worldSize: new google.maps.Size(1024, 512), // The heading in degrees at the origin of the panorama // tile set. centerHeading: 105, getTileUrl: getCustomPanoramaTileUrl } }; } } 参数实例化列表项架构。

示例:

many=True

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

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

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

答案 1 :(得分:1)

SimpleListInput是一个具有属性“items”的类。属性“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.']}

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

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

查看Validation

答案 2 :(得分:0)

请看看我写的一个小图书馆,它试图解决这个问题: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"]

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