How to create a “type-agnostic” SchemaNode in colander

放肆的年华 提交于 2019-12-12 14:11:05

问题


I'm trying to use colander to define a SchemaNode that could have any type. I'd like it to just take whatever was deserialized from the JSON and pass it along. Is that possible?

class Foo(colander.MappingSchema):
    name = colander.SchemaNode(colander.String(), validator=colander.Length(max=80))
    value = colander.SchemaNode(??) # should accept int, float, string...

回答1:


Those Colander types derive from SchemaType and implement the methods that actually do the serialisation and deserialisation.

The only way I can think of to do this is write your own implementation of SchemaType that is essentially a wrapper that tests the value and applies one of the types defined in Colander.

I don't think it would be that hard, just not pretty.

Edit: Here's a scratch example. I haven't tested it, but it conveys the idea.

class AnyType(SchemaType):

    def serialize(self, node, appstruct):
        if appstruct is null:
            return null

        impl = colander.Mapping()  # Or whatever default.
        t = type(appstruct)

        if t == str:
            impl = colander.String()
        elif t == int:
            impl = colander.Int()
        # Test the others, throw if indeterminate etc.

        return impl.serialize(node, appstruct)

    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        # Test and return again.



回答2:


I only needed the deserialization, so I used a simplified version of SpiritMachine's answer:

class AnyType(colander.SchemaType):
    def deserialize(self, node, cstruct):
        return cstruct

I might add something in later for date/datetime detection.



来源:https://stackoverflow.com/questions/23231792/how-to-create-a-type-agnostic-schemanode-in-colander

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!