棉花糖:将字典转换为元组

marshmallow: convert dict to tuple

鉴于

输入数据x是:

{'comm_name': 'XXX', 'comm_value': '1234:5678', 'dev_name': 'router-1'}

marshmallow架构如下:

class BGPcommunitiesPostgresqlSchema(marshmallow.Schema):
    comm_name = marshmallow.fields.Str(required=True)
    comm_value = marshmallow.fields.Str(required=True)

    @marshmallow.validates('comm_value')
    def check_comm_value(self, value):
        if value.count(":") < 1:
            raise marshmallow.ValidationError("a BGP community value should contain at least once the `:` char")
        if value.count(":") > 2:
            raise marshmallow.ValidationError("a BGP community value should contain no more than two `:` chars")

让我们加载它及其数据:

schema  = BGPcommunitiesPostgresqlSchema()
zzz = schema.load(x)

如果我们打印它,我们得到:

zzz.data
Out[17]: {'comm_name': u'XXX', 'comm_value': u'1234:5678'}

Objective: 我希望最终结果是:

In [20]: zzz.data
Out[20]: (u'XXX', u'1234:5678')

当我 zzz.data 而不是获取 dict 时,如何获得该结果(元组)?

根据 the docs,您可以在加载架构后为 return 对象定义一个 @post_load 装饰函数。

class BGPcommunitiesPostgresqlSchema(marshmallow.Schema):
    comm_name = marshmallow.fields.Str(required=True)
    comm_value = marshmallow.fields.Str(required=True)

    @marshmallow.validates('comm_value')
    def check_comm_value(self, value):
        if value.count(":") < 1:
            raise marshmallow.ValidationError("a BGP community value should contain at least once the `:` char")
        if value.count(":") > 2:
            raise marshmallow.ValidationError("a BGP community value should contain no more than two `:` chars")

    @marshmallow.post_load
    def value_tuple(self, data):
        return (data["comm_name"], data["comm_value"])