標籤:return 3.5 #### color dict name hal ali first
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 errorsMarshalResult = namedtuple(‘MarshalResult‘, [‘data‘, ‘errors‘])#: Return type of :meth:`Schema.load`, including deserialized data and errorsUnmarshalResult = 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 name33>>> p # readable __repr__ with a name=value stylePoint(x=11, y=22)
[Python]Marshmallow 代碼