1

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
   }
}
shredding
  • 5,374
  • 3
  • 46
  • 77
  • I don't know about Colander but the API contains [validators](http://docs.pylonsproject.org/projects/colander/en/latest/api.html#validators). Does any of these do what you want? –  Jan 07 '15 at 09:01

1 Answers1

3

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())
Janne Karila
  • 24,266
  • 6
  • 53
  • 94