pythoncolander

Prohibit unknown values?


Can I raise an error with colander, if values are in the payload that are not in the schema? Thus, allowing only whitelisted fields?

This is a sample:

# coding=utf-8
from colander import MappingSchema, String, Length
from colander import SchemaNode


class SamplePayload(MappingSchema):
    name = SchemaNode(String())
    foo  = SchemaNode(Int())


class Sample(MappingSchema):
    type = SchemaNode(String(), validator=Length(max=32))
    payload = SamplePayload()

# This json should not be accepted (and should yield something like: Unknown field in payload: bar

{  
   "type":"foo",
   "payload":{  
      "name":"a name",
      "foo":123,
      "bar":false
   }
}

Solution

  • Yes, see the docs of colander.Mapping

    Creating a mapping with colander.Mapping(unknown='raise') will cause a colander.Invalid exception to be raised when unknown keys are present in the cstruct during deserialization.

    According to issue 116 in the tracker, the way to apply this to a Schema object is to override the schema_type method:

    class StrictMappingSchema(MappingSchema):
        def schema_type(self, **kw):
            return colander.Mapping(unknown='raise')
    
    class SamplePayload(StrictMappingSchema):
        name = SchemaNode(String())
        foo  = SchemaNode(Int())