-
schema.dump和schema.load
schema.dump()方法返回一個MarshResult的對象,marshmallow官方API說dump和load方法返回的都是dict對象,但查看源碼,MarshResult對象是一個namedtuple.html
## 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的時候,這裏是有問題的python
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']的方法沒法訪問對象信息json
可是經過result.data['xxx']倒是OK的。Python Doc裏對namedtuple的問方式也是"."訪問。好像能夠理解爲name是namedtuple的一個attribute,url
>>> # 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)