我试图使用漏勺来定义可能具有任何类型的SchemaNode。我希望只从JSON中取出反序列化的内容并传递它。这可能吗?
class Foo(colander.MappingSchema):
name = colander.SchemaNode(colander.String(), validator=colander.Length(max=80))
value = colander.SchemaNode(??) # should accept int, float, string...
答案 0 :(得分:3)
这些漏勺类型派生自 SchemaType ,并实现实际进行序列化和反序列化的方法。
我能想到的唯一方法是编写自己的 SchemaType 实现,它本质上是一个包装器,用于测试值并应用Colander中定义的其中一种类型。
我认为这不会那么难,只是不漂亮。
编辑:这是一个划痕示例。我没有测试它,但它传达了这个想法。
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.
答案 1 :(得分:1)
我只需要反序列化,所以我使用了SpiritMachine答案的简化版本:
class AnyType(colander.SchemaType):
def deserialize(self, node, cstruct):
return cstruct
我可能稍后会在日期/日期时间检测中添加一些内容。