nskalis
nskalis

Reputation: 2382

convert object when serializing it

Given that :

class BGPcommunitiesElasticSchema(marshmallow.Schema):
    comm_name = marshmallow.fields.Str(required=True)
    comm_value = marshmallow.fields.Str(required=True, )
    dev_name = marshmallow.fields.Str(required=True)
    time_stamp = marshmallow.fields.Integer(missing=time.time())

    @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 colon char")
        if value.count(":") > 2:
            raise marshmallow.ValidationError("a BGP community value should contain no more than two colon chars")

    # @marshmallow.pre_dump
    # def rename_comm_value(self, data):
    #     return data['comm_value'].replace(":","_")

How can I manipulate the field comm_value before serializing it ?

The field comm_value is a string for example 1234:5678 and I would like to convert it to 1234_5678.

Could you please advise on how to achieve that ?

PS. pre_dump looks the right way of doing it, but I am not sure since it is my first day using marshmallow

Upvotes: 0

Views: 6558

Answers (2)

naoko
naoko

Reputation: 5226

Looks like you want to work with serialized object (dict) and the best place might be then post_dump

from marshmallow import Schema, post_dump
class S(marshmallow.Schema):
    a = marshmallow.fields.Str()
    @post_dump
    def rename_val(self, data):
        data['a'] = data['a'].replace(":", "_")
        return data

>>> S().dumps(dict(a="abc:123"))
MarshalResult(data='{"a": "abc_123"}', errors={})

Upvotes: 1

dizzyf
dizzyf

Reputation: 3693

pre_dump can do what you want, but I would use a class method instead:

class BGPcommunitiesElasticSchema(marshmallow.Schema):
    comm_name = marshmallow.fields.Str(required=True)
    comm_value = marshmallow.fields.Method("comm_value_normalizer", required=True)
    dev_name = marshmallow.fields.Str(required=True)
    time_stamp = marshmallow.fields.Integer(missing=time.time())


    @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 colon char")
        if value.count(":") > 2:
            raise marshmallow.ValidationError("a BGP community value should contain no more than two colon chars")

    @classmethod
    def comm_value_normalizer(cls, obj):
        return obj.comm_value.replace(":", "_")

You could also create your own comm_value_normalized attribute that way if you want the original "comm_value" to remain untouched.

Upvotes: 1

Related Questions