[Python]Marshmallow 代碼

來源:互聯網
上載者:User

標籤: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 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 代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.