Python 科兰德:我如何允许无值?
假设我有一个简单的模式:Python 科兰德:我如何允许无值?,python,colander,Python,Colander,假设我有一个简单的模式: class MySchema(colander.MappingSchema): thing = colander.SchemaNode(colander.Int()) 使用上面的模式,当尝试反序列化{'thing':None}时,我得到错误: Invalid: {'thing': u'Required'} 看起来colander对待None值的字段与缺少字段的处理方式相同。我如何才能绕过这一点并强制执行总是提供东西,但允许它是无?无值将用于反序列化,但是您需
class MySchema(colander.MappingSchema):
thing = colander.SchemaNode(colander.Int())
使用上面的模式,当尝试反序列化{'thing':None}
时,我得到错误:
Invalid: {'thing': u'Required'}
看起来colander对待
None
值的字段与缺少字段的处理方式相同。我如何才能绕过这一点并强制执行总是提供东西
,但允许它是无
?无值将用于反序列化,但是您需要在模式中提供一个“缺少”参数:
class MySchema(colander.MappingSchema):
thing = colander.SchemaNode(colander.Int(), missing=None)
< P>请考虑此解决方案。
import colander
class NoneAcceptantNode(colander.SchemaNode):
"""Accepts None values for schema nodes.
"""
def deserialize(self, value):
if value is not None:
return super(NoneAcceptantNode, self).deserialize(value)
class Person(colander.MappingSchema):
interest = NoneAcceptantNode(colander.String())
# Passes
print Person().deserialize({'interest': None})
# Passes
print Person().deserialize({'interest': 'kabbalah'})
# Raises an exception
print Person().deserialize({})
这是我用的。我将空字符串映射到显式空值。如果required标志为true,则会引发无效错误
from colander import SchemaNode as SchemaNodeNoNull
class _SchemaNode(SchemaNodeNoNull):
nullable = True
def __init__(self, *args, **kwargs):
# if this node is required but nullable is not set, then nullable is
# implicitly False
if kwargs.get('missing') == required and kwargs.get('nullable') is None:
kwargs['nullable'] = False
super(_SchemaNode, self).__init__(*args, **kwargs)
def deserialize(self, cstruct=null):
if cstruct == '':
if not self.nullable:
raise Invalid(self, _('Cannot be null'))
if self.validator:
self.validator(self, cstruct)
return None # empty string means explicit NULL value
ret = super(_SchemaNode, self).deserialize(cstruct)
return ret
此外,在处理querystring参数时,foo=,bar=将变为:
{
"foo": "",
"bar": ""
}
文本空值仅在JSON有效负载时才可能出现,这没有帮助:正如您链接的页面中突出显示的,使用
colander.null
仍将引发无效的异常colander.null
和缺少的值对于colander几乎是一样的。我的问题是,None
似乎也被同样对待,尽管我找不到任何关于这种行为的文档。啊,好吧,看起来你实际上需要在你的模式中设置一个默认的缺失值。我已经更新了我的答案,包括这个。仍然没有做我想做的。。。使用missing=None
时,即使东西不存在,它也会被添加并设置为None
。如果thing
未出现在我希望引发的数据中,则不会自动添加它。是否希望引发错误?这不是已经发生了吗?我想在东西不存在时引发一个错误。如果存在东西
(即使是无
),我不希望引发错误。