marshmallow: convert dict to tuple

拜拜、爱过 提交于 2019-12-12 02:44:42

问题


Given that

the input data x are:

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

The marshmallow schema is as follows:

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")

Let's load it and its data:

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

If we print that, we get:

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

Objective: I would like the end result to be:

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

How can I achieve that result (tuple) when I do zzz.data instead of getting the dict ?


回答1:


According to the docs you can define a @post_load decorated function to return an object after loading the schema.

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"])


来源:https://stackoverflow.com/questions/44166325/marshmallow-convert-dict-to-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!