Catch an empty colander list

I use colander to check (and deserialize json data) input of some web services.

I would like to add a rule to the colander scheme to catch an empty list, but I cannot figure out how to do this.

Now I have the following example demonstrating a call to f() with two different data sets. I would like the colander.Invalid exception to be colander.Invalid due to 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?

+6
source share
1 answer

Have you tried using the colander.Length validator?

Try changing the scheme:

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

For bad_data this should boost:

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

Source: https://habr.com/ru/post/953223/


All Articles