序列化时转换对象

时间:2017-05-24 15:08:41

标签: python marshmallow

鉴于:

  ISNULL(A.Exit, Getdate()) > PeriodStart

如何在序列化之前操作字段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

请问您如何实现这一目标?

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

2 个答案:

答案 0 :(得分:0)

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

如果您想要原始&#34; comm_value&#34>,您也可以创建自己的comm_value_normalized属性。保持不变

答案 1 :(得分:0)

看起来像您要使用序列化对象(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={})