Hi all,
I'm using colander to validate json input for my api. To report the
invalid input to user
I try to unflatten the invalid.asdict()
However if the invalid input located in the place other than the first
place in a
sequence the unflatten fails.
Here is the snipets: (as
https://gist.github.com/2641011 )
import colander
class Phone(colander.MappingSchema):
location = colander.SchemaNode(colander.String(),
validator=colander.OneOf(['home', 'work']))
number = colander.SchemaNode(colander.String())
class Phones(colander.SequenceSchema):
phone = Phone()
class User(colander.MappingSchema):
name = colander.SchemaNode(colander.Str())
phones = Phones()
user = User()
d1 = {'name': 'jim',
'phones': [{'location': 'office', 'number': '12343'},
{'location': 'home', 'number': '33131'}]
}
try:
user.deserialize(d1)
except colander.Invalid as invalid:
print user.unflatten(invalid.asdict())
# result:
# {'phones': [{'location': u'"office" is not one of home, work'}]}
# place invalid location as second position
d2 = {'name': 'bob',
'phones': [{'location': 'home', 'number': '1234'},
{'location': 'office', 'number': '33131'}]
}
try:
user.deserialize(d2)
except colander.Invalid as invalid:
print user.unflatten(invalid.asdict())
# result:
# ...
# /opt/env/lib/python2.7/site-packages/colander/__init__.py", line
816, in unflatten
# return [mapstruct[str(index)] for index in xrange(len(mapstruct))]
# KeyError: '0'
#
How to handle this error or is there a better way to show the error in
a api (json) validation?
thanks,