python - 用漏勺捕捉空列表

标签 python colander

我正在使用 colander 来验证(和反序列化 json 数据)对一些网络服务的输入。

我想向漏勺模式添加规则以捕获空列表,但我不知道该怎么做。

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

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

对于 bad_data 这应该引发:

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

关于python - 用漏勺捕捉空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18632562/

相关文章:

Python - 始终将某些字符串附加到列表的末尾

python - Colander 和 Cornice 无法正常工作

python - 如何在漏勺形式中使用列表或数组

python - 使用变形的相关/级联输入

python - 使用 Colander 验证 PATCH 请求

python - 使用 Pyramid 在 View 和应用程序之间共享对象

python - 在 python 中屏蔽然后粘贴两个图像

python - 如何检查此用户是匿名用户还是我系统上的实际用户?

python - 如何禁止程序请求 sudo 权限?

带有 urlencoded 多维字典的 Python POST