Variable dictionary in Colander
سؤال
How can I validate following data structure using colander library?
[
{
'bar': ['a', 'b', 'c'],
'variable2': ['b', 'c'],
'foo': ['a', 'c'],
},
{
'something': ['foo', 'bar'],
},
]
The problem is that these mapping can have any number of key-value pairs, and keys namespace is not restricted. I also want to make sure that each key is a string and each value is a sequence of strings.
I could use Mapping(unknown='preserve')
, but it won't validate the types.
المحلول
Looking at the documentation, I don't think you can. You could get around the limitation you mentioned by defining your own validator:
A validator is a callable which accepts two positional arguments:
node
andvalue
. It returnsNone
if the value is valid. It raises acolander.Invalid
exception if the value is not valid.
نصائح أخرى
I did that but it doesn't seams to work:
class PolicyValidator(SchemaNode):
def __init__(self):
super(PolicyValidator, self).__init__(
Mapping(unknown='preserve'), validator=self.policy_range)
# self.add(SchemaNode(Range(min=0, max=0xFFFF), name="preserved"))
def policy_range(self, node, policy):
for value in policy.itervalues():
if value < 0 or value > 0xFFFF:
raise Invalid(node, '%r is not a valid permission.' % value)
I find another solution:
class PolicyValidator(SchemaNode):
def __init__(self, policy):
super(PolicyValidator, self).__init__(Mapping(unknown='preserve'))
for key in policy.iterkeys():
self.add(SchemaNode(Int(), name=key,
validator=Range(min=0, max=0xFFFF)))