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?
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({})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With