marshmallow: convert dict to tuple

2019-08-21 02:06发布

问题:

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