我有一个父棉花糖模式"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 原则并将该函数拉出 ParentSchema.py。
我发现的一个解决方案是创建一个单独的类来托管共享验证函数:
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 从棉花糖导入验证错误,验证
def validate_common_field(self, common_field):
try:
# Validation logic
except:
raise ValidationError('common_field is not valid')
您使用单独函数的方法很好。
如果公共字段由两个子字段共享,则还可以使用继承来反映这一点,并对字段和逻辑进行分解。
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()