I'm using colander for deserialization and validation json data.
I need process special values infinity
and -infinity
in date fields.
But colander.Date
doesn't support such value.
class Card(colander.MappingSchema):
card_no = colander.SchemaNode(colander.String())
expiration = colander.SchemaNode(colander.Date())
cstruct = {'card_no': '12345', 'expiration': 'infinity'}
schema = Card()
output = schema.deserialize(cstruct)
I have output
colander.Invalid: {'expiration': 'Invalid date'}
My working code is:
def modify(nodes, kw):
for node in nodes:
if (type(node.typ) == colander.Date):
if kw[node.name] == 'infinity':
kw[node.name] = str(datetime.max)
cstruct = {'card_no': '12345', 'expiration': 'infinity'}
schema = Card(after_bind=modify)
schema = schema.bind(**cstruct)
output = schema.deserialize(schema.bindings)
print(output)
I have output
{'card_no': '12345', 'expiration': datetime.date(9999, 12, 31)}
But I'm not sure, if it is a good idea to do it this way.
Or should I rather define custom colander type for date fields and use it instead of colander.Date
?