这是我正在使用的。我将空字符串映射到显式空值。如果 required 标志为真,则会引发无效错误。
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
此外,在处理查询字符串参数时, foo=,bar= 将变为:
{
"foo": "",
"bar": ""
}
文字空值仅适用于 JSON 有效负载