2017-05-24 97 views
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

回答

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」保持不變。

+0

如果你有時間可以請你也建議在https://stackoverflow.com/questions/44166325/marshmallow-convert-dict-to-tuple我想知道如果這將是可能的:) – iamsterdam