0

鉴于 :

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

4

2 回答 2

1

看起来您想使用序列化对象(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={})
于 2019-06-17T22:46:15.227 回答
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(":", "_")

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

于 2017-05-24T16:37:35.123 回答