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...
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.