如何创建“类型不可知"漏勺中的 SchemaNode [英] How to create a "type-agnostic" SchemaNode in colander

查看:51
本文介绍了如何创建“类型不可知"漏勺中的 SchemaNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用漏勺来定义一个可以具有任何类型的 SchemaNode.我希望它只获取从 JSON 反序列化的任何内容并将其传递.这可能吗?

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...

推荐答案

那些漏勺类型派生自 SchemaType 并实现实际执行序列化和反序列化的方法.

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

我能想到的唯一方法是编写您自己的 SchemaType 实现,它本质上是一个包装器,用于测试值并应用漏勺中定义的类型之一.

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.

这是一个草稿示例.我还没有测试过,但它传达了这个想法.

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.

这篇关于如何创建“类型不可知"漏勺中的 SchemaNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆