序列化时转换对象

convert object when serializing it

鉴于:

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(":","_")

如何在序列化之前操作字段 comm_value

字段 comm_value 是一个字符串,例如 1234:5678,我想将其转换为 1234_5678

能否就如何实现这一点提出建议?

PS。 pre_dump 看起来是正确的做法,但我不确定,因为这是我第一天使用 marshmallow

pre_dump 可以做你想做的事,但我会用 class 方法代替:

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(":", "_")

如果您希望原始 "comm_value" 保持不变,您也可以通过这种方式创建自己的 comm_value_normalized 属性。

您似乎想使用序列化对象 (dict) 最好的地方可能是 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={})