用可变键和数组值的映射的colander模式

12 投票
3 回答
2605 浏览
提问于 2025-04-17 21:00

我该如何在colander中为以下形式的JSON定义模式呢?

{
    'data' : {
        'key_1' : [123, 567],
        'key_2' : ['abc','def'],
        'frank_underwood' : [666.66, 333.333],
        ... etc ...
    }
}

在'data'里面的键可以是任何字符串,而它的值是数组。

目前,我有以下的代码,但这并没有对映射中值的类型设定任何限制。

class Query(colander.MappingSchema):
    data = colander.SchemaNode(
        colander.Mapping(unknown='preserve'),
        missing={}
    )

那么,正确的描述方式是什么呢?

3 个回答

1

我找到了一种其他的方法。

from colander import SchemaType, Invalid
import json

class JsonType(SchemaType):
   ...
   def deserialize(self, node, cstruct):
    if not cstruct: return null
    try:
        result = json.loads(cstruct, encoding=self.encoding)
    except Exception as e:
        raise Invalid(node,"Not json ...")
    return result

如何在colander中创建一个“类型无关”的SchemaNode

1

我不知道colander是什么,但你可以试试Spyne。

class Data(ComplexModel):
    key_1 = Array(Integer)
    key_2 = Array(Unicode)
    frank_underwood = Array(Double)

class Wrapper(ComplexModel):
    data = Data

这里有一个完整的示例:https://gist.github.com/plq/3081280856ed1c0515de

Spyne的模型文档在这里:http://spyne.io/docs/2.10/manual/03_types.html


不过,看来这并不是你需要的。如果你想要一个更灵活的字典,那么你需要使用自定义类型:

class DictOfUniformArray(AnyDict):
    @staticmethod  # yes staticmethod
    def validate_native(cls, inst):
        for k, v in inst.items():
            if not isinstance(k, six.string_types):
                raise ValidationError(type(k), "Invalid key type %r")
            if not isinstance(v, list):
                raise ValidationError(type(v), "Invalid value type %r")
            # log_repr prevents too much data going in the logs.
            if not len(set(map(type, v))) == 1:
                raise ValidationError(log_repr(v),
                                      "List %s is not uniform")
        return True

class Wrapper(ComplexModel):
    data = DictOfUniformArray

这里有一个完整的示例:https://github.com/arskom/spyne/blob/spyne-2.12.5-beta/examples/custom_type.py

6

一个可能的解决办法是使用一个自定义验证器

下面是一个完整的示例,这个自定义验证器可以检查一个任意的映射(map)中的所有值是否都是单一类型的数组。

import colander


def values_are_singularly_typed_arrays(node, mapping):
    for val in mapping.values():
        if not isinstance(val, list):
            raise colander.Invalid(node, "one or more value(s) is not a list")
        if not len(set(map(type, val))) == 1:
            raise colander.Invalid(node, "one or more value(s) is a list with mixed types")

class MySchema(colander.MappingSchema):
    data = colander.SchemaNode(
        colander.Mapping(unknown='preserve'),
        validator=values_are_singularly_typed_arrays
    )

def main():
    valid_data = {
        'data' : {
            'numbers' : [1,2,3],
            'reals' : [1.2,3.4,5.6],
        }
    }
    not_list = {
        'data' : {
            'numbers' : [1,2,3],
            'error_here' : 123
        }
    }
    mixed_type = {
        'data' : {
            'numbers' : [1,2,3],
            'error_here' : [123, 'for the watch']
        }
    }

    schema = MySchema()
    schema.deserialize(valid_data)

    try:
        schema.deserialize(not_list)
    except colander.Invalid as e:
        print(e.asdict())

    try:
        schema.deserialize(mixed_type)
    except colander.Invalid as e:
        print(e.asdict())

if __name__ == '__main__':
    main()

撰写回答