我有一个父棉花糖架构“ ParentSchema”和2个嵌套子架构“ ChildSchema1”和“ ChildSchema2”。两种嵌套子模式都利用@validates_schema装饰器从棉花糖进行字段验证。他们看起来像这样:
ParenSchema.py
from marshmallow import Schema, fields
from schemas.childSchema1 import ChildSchema1
from schemas.childSchema2 import ChildSchema2
class ParentSchema(Schema):
child1 = fields.Nested(ChildSchema1)
child2 = fields.Nested(ChildSchema2)
foo = fields.String()
bar = fields.String()
ChildSchema1.py
from marshmallow import Schema, pprint, post_load
from marshmallow import fields, ValidationError, validates, validates_schema
class ChildSchema1(Schema):
field1 = fields.String()
field2 = fields.String()
common_field = fields.String()
@validates("common_field")
def validate_common_field(self, common_field):
try:
# Validation logic
except:
raise ValidationError('common_field is not valid')
ChildSchema2.py
from marshmallow import Schema, pprint, post_load
from marshmallow import fields, ValidationError, validates, validates_schema
class ChildSchema2(Schema):
common_field = fields.String()
field3 = fields.String()
@validates("common_field")
def validate_common_field(self, common_field):
try:
# Exact Same Validation logic as common_field from ChildSchema1
except:
raise ValidationError('common_field is not valid')
鉴于ChildSchema1和ChildSchema2都具有相同名称的字段,并且具有相同的验证函数,我很乐意遵循DRY Principle并将该函数拉到ParentSchema.py。
答案 0 :(得分:0)
我发现一个解决方案是创建一个单独的类来托管共享验证功能:
def validate_common_field(self, common_field):
try:
# Exact Same Validation logic as common_field from ChildSchema1
except:
raise ValidationError('common_field is not valid')
并通过删除@validates装饰器并在架构字段中使用validate
参数来从ChildSchema1和ChildSchema2中使用它。
ChildSchema1.py
from marshmallow import Schema, pprint, post_load
from marshmallow import fields, ValidationError, validates, validates_schema
from validators import *
class ChildSchema1(Schema):
field1 = fields.String()
field2 = fields.String()
common_field = fields.String(validate=validate_common_field)
validators.py 从棉花糖导入ValidationError,进行验证
def validate_common_field(self, common_field):
try:
# Validation logic
except:
raise ValidationError('common_field is not valid')
答案 1 :(得分:0)
您可以使用具有单独功能的方法。
如果两个孩子都共享公共字段,则还可以使用继承来反映这一点,并分解该字段和逻辑。
class ChildSchema(Schema):
common_field = fields.String()
@validates("common_field")
def validate_common_field(self, common_field):
try:
# Validation logic
except:
raise ValidationError('common_field is not valid')
class ChildSchema1(ChildSchema):
field1 = fields.String()
field2 = fields.String()
class ChildSchema2(ChildSchema):
field3 = fields.String()