Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用滤器捕捉空列表_Python_Colander - Fatal编程技术网

Python 用滤器捕捉空列表

Python 用滤器捕捉空列表,python,colander,Python,Colander,我正在使用colander验证(并反序列化json数据)对某些web服务的输入 我想在colander模式中添加一个规则来捕获空列表,但我不知道该怎么做 现在我有下面的示例,演示了使用两组不同的数据调用函数f()。我希望后者触发colander.Invalid异常,因为事件列表为空 import colander def f(data): class EventList(colander.SequenceSchema): list_item = colander.Sch

我正在使用
colander
验证(并反序列化json数据)对某些web服务的输入

我想在colander模式中添加一个规则来捕获空列表,但我不知道该怎么做

现在我有下面的示例,演示了使用两组不同的数据调用函数
f()
。我希望后者触发
colander.Invalid
异常,因为
事件列表为空

import colander

def f(data):
    class EventList(colander.SequenceSchema):
        list_item = colander.SchemaNode(colander.Int())

    class Schema(colander.MappingSchema):
        txt    = colander.SchemaNode(colander.String())
        user   = colander.SchemaNode(colander.String())
        events = EventList()

    try:
        good_data = Schema().deserialize(data)
        print 'looks good'
    except colander.Invalid as e:
        print "man, your data suck"


good_data = {'txt' : 'BINGO',
             'user' : 'mogul',
             'events' : [11, 22, 33]}
f(good_data)

bad_data = {'txt' : 'BOOM',
            'user' : 'mogul',
            'events' : []}
f(bad_data)

建议

您是否尝试过使用
colander.Length
验证程序

尝试使用以下内容修改您的架构:

events = EventList(validator=colander.Length(min=1))
对于
错误的\u数据
这将引发:

Invalid: {'events': u'Shorter than minimum length 1'}

猛敲完全正确谢谢你,伙计!在这条线的某个地方,我几乎试过了,但没能做到恰到好处。当你需要时,“捐赠啤酒”按钮在哪里?