Catch empty list with colander

1.4k views Asked by At

I'm using colander to validate (and deserialize json data) input to some web services.

I would like to add a rule to a colander schema to catch an empty list, but I can not figure out how to do it.

Right now I have the following example, demonstrating a call to the function f() with two different sets of data. I would like the later to trigger the colander.Invalid exception because of the empty events list

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)

Suggestions?

1

There are 1 answers

1
Jules Olléon On BEST ANSWER

Have you tried using the colander.Length validator?

Try to modify your schema with:

events = EventList(validator=colander.Length(min=1))

For bad_data this should raise:

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