3

単純なスキーマがあるとします:

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int())

上記のスキーマで逆シリアル化しようとすると{'thing': None}、次のエラーが発生します。

Invalid: {'thing': u'Required'}

colander はNone値のあるフィールドを欠落しているフィールドと同じように扱うようです。どうすればそれを回避し、thing常に提供されるようにすることができますNoneか?

4

3 に答える 3

4

この解決策を検討してください。

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({})
于 2013-12-02T16:23:09.627 に答える
2

None 値は逆シリアル化に機能しますが、スキーマに「不足している」引数を指定する必要があります。

class MySchema(colander.MappingSchema):
    thing = colander.SchemaNode(colander.Int(), missing=None)

http://docs.pylonsproject.org/projects/colander/en/latest/null.html#deserializing-the-null-value

于 2013-09-13T00:12:00.553 に答える
0

これが私が使用しているものです。空の文字列を明示的な null 値にマップしています。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

また、クエリ文字列パラメータを扱う場合、foo=,bar= は次のようになります。

{
   "foo": "",
   "bar": ""
}

リテラルの null 値は、JSON ペイロードでのみ可能です

于 2016-11-10T19:13:30.653 に答える