1. 程式人生 > >[Python]Marshmallow 代碼

[Python]Marshmallow 代碼

TP shmall unmarshal position str marshal field HR error:

  • 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 代碼