鉴于此
输入数据x
为:
{'comm_name': 'XXX', 'comm_value': '1234:5678', 'dev_name': 'router-1'}
marshmallow
架构如下:
class BGPcommunitiesPostgresqlSchema(marshmallow.Schema):
comm_name = marshmallow.fields.Str(required=True)
comm_value = marshmallow.fields.Str(required=True)
@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 `:` char")
if value.count(":") > 2:
raise marshmallow.ValidationError("a BGP community value should contain no more than two `:` chars")
让我们加载它及其数据:
schema = BGPcommunitiesPostgresqlSchema()
zzz = schema.load(x)
如果我们打印出来,我们会得到:
zzz.data
Out[17]: {'comm_name': u'XXX', 'comm_value': u'1234:5678'}
目标:我希望最终结果为:
In [20]: zzz.data
Out[20]: (u'XXX', u'1234:5678')
当我zzz.data
而不是获取字典时,如何实现该结果(元组)?
答案 0 :(得分:1)
根据the docs,你可以定义一个@post_load
修饰函数,以在加载模式后返回一个对象。
class BGPcommunitiesPostgresqlSchema(marshmallow.Schema):
comm_name = marshmallow.fields.Str(required=True)
comm_value = marshmallow.fields.Str(required=True)
@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 `:` char")
if value.count(":") > 2:
raise marshmallow.ValidationError("a BGP community value should contain no more than two `:` chars")
@marshmallow.post_load
def value_tuple(self, data):
return (data["comm_name"], data["comm_value"])