zoukankan      html  css  js  c++  java
  • [Python]Marshmallow 代码

    • 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)
  • 相关阅读:
    单例模式
    抽象类的作用和应用场景
    java内部类的作用
    java多线程
    IO流--与properties集合配合使用
    IO流--序列化流与反序列化流
    8 个必备的PHP功能开发
    CSS3 box-shadow:
    移动平台的meta标签-----神奇的功效
    Android Screen Monitor抓取真机屏幕
  • 原文地址:https://www.cnblogs.com/oDoraemon/p/9249856.html
Copyright © 2011-2022 走看看