Skip to content Skip to sidebar Skip to footer

Marshmallow: Convert Dict To Tuple

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

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

Post a Comment for "Marshmallow: Convert Dict To Tuple"