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)
  • 相关阅读:
    jquery加入购物车飞入的效果
    jQuery点击div其他地方隐藏div
    移动对meta的定义
    ZOJ
    博弈dp入门 POJ
    ZOJ 2967计算几何+单调栈
    牛客训练41D最小相似度bfs
    球的体积并
    二进制上的数位dpPOJ 3252
    数位dp入门 HDU 2089 HDU 3555
  • 原文地址:https://www.cnblogs.com/oDoraemon/p/9249856.html
Copyright © 2011-2022 走看看