Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch empty list with colander

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?

like image 661
mogul Avatar asked Sep 05 '13 09:09

mogul


1 Answers

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'}
like image 158
Jules Olléon Avatar answered Sep 22 '22 00:09

Jules Olléon