序列化i时转换对象

2024-05-14 23:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于:

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


Tags: nameselftruefieldsiftimevaluedef
2条回答

pre_dump可以做任何您想要的,但是我将使用一个类方法来代替:

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\u 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={})

相关问题 更多 >

    热门问题