棉花糖:将dict转换为tup

2024-10-03 23:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于此

输入数据x是:

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

marshmallow模式如下:

^{pr2}$

让我们加载它及其数据:

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时,如何实现这个结果(tuple)?在


Tags: 数据namedevdatavalueschema模式out
1条回答
网友
1楼 · 发布于 2024-10-03 23:23:55

根据the docs,您可以定义一个@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"])

相关问题 更多 >