0

鉴于

输入数据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'}

目标:我希望最终结果是:

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

zzz.data当我这样做而不是获取 dict时,如何实现该结果(元组) ?

4

1 回答 1

1

根据文档,您可以定义一个@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"])
于 2017-05-24T19:02:08.913 回答