Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colander: how do I allow None values?

Say I have a simple schema:

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int())

With the schema above, when trying to deserialize {'thing': None} I get the error:

Invalid: {'thing': u'Required'}

It looks like colander treats fields with a None value the same way as missing fields. How can I get around that and enforce that thing is always provided, but allow it to be None?

like image 940
Jules Olléon Avatar asked Apr 13 '26 10:04

Jules Olléon


2 Answers

Please consider this solution.

import colander


class NoneAcceptantNode(colander.SchemaNode):
    """Accepts None values for schema nodes.
    """

    def deserialize(self, value):
        if value is not None:
            return super(NoneAcceptantNode, self).deserialize(value)


class Person(colander.MappingSchema):
    interest = NoneAcceptantNode(colander.String())


# Passes
print Person().deserialize({'interest': None})

# Passes
print Person().deserialize({'interest': 'kabbalah'})

# Raises an exception
print Person().deserialize({})
like image 53
negus Avatar answered Apr 14 '26 23:04

negus


A None value will work for deserialization, however you need to supply a 'missing' argument in your schema:

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int(), missing=None)

http://docs.pylonsproject.org/projects/colander/en/latest/null.html#deserializing-the-null-value

like image 26
Rohmer Avatar answered Apr 14 '26 23:04

Rohmer