0

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?

Horned Owl
  • 139
  • 2
  • 9
  • 1
    I suspect the problem here is that there is no conversion between infinite values and date in Python. Use MAXYEAR and MINYEAR instead, or have a flag to represent whatever you're trying to represent. – Marcin Sep 11 '14 at 12:51
  • Do you mean that I would use cstruct = {'card_no': '12345', 'expiration': '9999-12-31'}? – Horned Owl Sep 11 '14 at 17:18
  • Yes. Also, look at jsonpickle if you want an alternative serializer (disclosure: I'm a co-author). – Marcin Sep 11 '14 at 18:20
  • Thank you for pointing out jsonpickle library. I'm using colander for validation json data before processing in sqlalchemy. It seems to me jsonpickle doesn't provide validation. – Horned Owl Sep 11 '14 at 22:09
  • That's correct. You'd still need to use a separate validator if that's what you need. – Marcin Sep 11 '14 at 22:58
  • As @Marcin suggested, value '9999-12-31' can be used instead of 'infinity'. I think it is a good idea. Colander can automatically deserialize it and my code remains simple. – Horned Owl Sep 14 '14 at 20:20

0 Answers0