码迷,mamicode.com
首页 > 编程语言 > 详细

[Python]Marshmallow 代码

时间:2018-07-01 13:36:56      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:return   3.5   ####   color   dict   name   hal   ali   first   

  • 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)

 

[Python]Marshmallow 代码

标签:return   3.5   ####   color   dict   name   hal   ali   first   

原文地址:https://www.cnblogs.com/oDoraemon/p/9249856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!