marshmallow: 簡化Python對象系列化

jopen 8年前發布 | 25K 次閱讀 Python開發 marshmallow

marshmallow -一個輕量級的庫用于將復雜對象轉成簡單的Python數據類型。或從簡單的Python數據類型轉成復雜對象。

from datetime import date
from marshmallow import Schema, fields, pprint

class ArtistSchema(Schema): name = fields.Str()

class AlbumSchema(Schema): title = fields.Str() release_date = fields.Date() artist = fields.Nested(ArtistSchema)

bowie = dict(name='David Bowie') album = dict(artist=bowie, title='Hunky Dory', release_date=date(1971, 12, 17))

schema = AlbumSchema() result = schema.dump(album) pprint(result.data, indent=2)

{ 'artist': {'name': 'David Bowie'},

'release_date': '1971-12-17',

'title': 'Hunky Dory'}</pre></div>

In short, marshmallow schemas can be used to:

  • Validate input data.
  • Deserialize input data to app-level objects.
  • Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.

Get It Now

$ pip install -U marshmallow

Documentation

Full documentation is available at http://marshmallow.readthedocs.org/ .

Requirements

  • Python >= 2.6 or >= 3.3

marshmallow has no external dependencies outside of the Python standard library, although python-dateutil is recommended for robust datetime deserialization.

Ecosystem

A list of marshmallow-related libraries can be found at the GitHub wiki here:

https://github.com/marshmallow-code/marshmallow/wiki/Ecosystem

Project Links

License

MIT licensed. See the bundled LICENSE file for more details.


項目地址: https://github.com/marshmallow-code/marshmallow

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!