禁止未知的价值观?

时间:2015-01-07 08:56:50

标签: python colander

如果值位于模式中没有的有效负载中,是否可以使用漏勺引发错误?因此,只允许列入白名单的字段?

这是一个示例:

# 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
   }
}

1 个答案:

答案 0 :(得分:2)

是的,请参阅the docs of colander.Mapping

使用colander.Mapping(unknown='raise')创建映射将导致在反序列化期间cstruct中存在未知密钥时引发colander.Invalid异常。

根据issue 116 in the tracker,将其应用于Schema对象的方法是覆盖schema_type方法:

class StrictMappingSchema(MappingSchema):
    def schema_type(self, **kw):
        return colander.Mapping(unknown='raise')

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