[Python]Marshmallow 代码

  • schema.dump和schema.load

schema.dump()方法返回一个MarshResult的对象,marshmallow官方API说dump和load方法返回的都是dict对象,但查看源码,MarshResult对象是一个namedtuple.

## marshmallow::schema.py

### line 25 ####

#
: Return type of :meth:`Schema.dump` including serialized data and errors MarshalResult = namedtuple('MarshalResult', ['data', 'errors']) #: Return type of :meth:`Schema.load`, including deserialized data and errors UnmarshalResult = namedtuple('UnmarshalResult', ['data', 'errors'])

我在跑官方Example的时候,这里是有问题的

    try:
        data = quote_schema.load(json_data)
    except ValidationError as err:
        return jsonify(err.messages), 422
    first, last = data['author']['first'], data['author']['last'] # 此处代码报错, TypeError: tuple indices must be integers or slices, not str

namedtuple通过result['data']['xxx']的方法无法访问对象信息

但是通过result.data['xxx']却是OK的。Python Doc里对namedtuple的问方式也是"."访问。好像可以理解为name是namedtuple的一个attribute,

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

 

posted @ 2018-07-01 12:59  oDoraemon  阅读(752)  评论(0编辑  收藏  举报