If I understand you correctly, it's not the post_load decorator you have an issue with it's the redundancy of maintaining two object definitions.
(如果我对您的理解正确,那么不是post_load装饰器存在问题,因为它是维护两个对象定义的冗余。)
If that's the case, you can use namedtuple or dataclasses to achieve what you want. (在这种情况下,您可以使用namedtuple或数据类来实现所需的功能。)
You would still define a post_load method on your schema but would not longer have to maintain a second class definition. (您仍将在架构上定义post_load方法,但不再需要维护第二个类定义。)
namedtuple solution
(元组解决方案)
from collections import namedtuple
def make_object(class_name, members):
obj = namedtuple(class_name, ' '.join(members.keys()))
for k, v in members.items():
setattr(obj, k, v)
return obj
dataclasses solution
(数据类解决方案)
from dataclasses import make_dataclass
def make_object(class_name, members):
obj = make_dataclass(class_name, [(k, type(v)) for k,v in members.items()])
for k, v in members.items():
setattr(obj, k, v)
return obj
class ProfileSchema(Schema):
id = fields.Integer()
first_name = fields.String(required=True)
last_name = fields.String()
phone = fields.Str()
email = fields.Email()
gender = fields.String()
city = fields.Str()
state = fields.Str()
country = fields.Str()
age = fields.Int()
id_proof = fields.Str()
id_number = fields.Str()
id_kyc_url = fields.Str()
image_url = fields.Str()
profile_type = fields.Str()
country_code = fields.String()
@validates('gender')
def validate_gender(self, value):
"""
validates gender
:param value:
:return:
"""
if value not in genders:
raise ValidationError('Incorrect gender value it should be either Male or Female')
@post_load
def make_profile(self, data):
"""
make profile obj
:param data:
:return:
"""
return make_object(data)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…