使用棉花糖而不重复自己 [英] Using Marshmallow without repeating myself
问题描述
根据Marshmallow官方文档,建议声明一个Schema,然后使用一个单独的类来接收已加载的数据,如下所示:
According to the official Marshmallow docs, it's recommended to declare a Schema and then have a separate class that receives loaded data, like this:
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
created_at = fields.DateTime()
@post_load
def make_user(self, data):
return User(**data)
但是,我的 User
类看起来像这样:
However, my User
class would look something like this:
class User:
def __init__(name, email, created_at):
self.name = name
self.email = email
self.created_at = created_at
这似乎在不必要地重复自己,我真的不喜欢写该属性又命名了三遍。但是,我喜欢对定义良好的结构进行IDE自动补全和静态类型检查。
This seems like repeating myself unnecessarily and I really don't like having to write the attribute names three more times. However, I do like IDE autocompletion and static type checking on well-defined structures.
那么,是否有最佳实践根据棉花糖模式加载序列化数据而不定义另一个类?
So, is there any best practice for loading serialized data according to a Marshmallow Schema without defining another class?
推荐答案
对于普通的Python类,没有一种现成的方式为模式定义类而不重复字段名称。
For vanilla Python classes, there isn't an out-of-box way to define the class for the schema without repeating the field names.
例如,如果您使用的是SQLAlchemy,则可以直接使用 marshmallow_sqlalchemy.ModelSchema
:
If you're using SQLAlchemy for example, you can define the schema directly from the model with marshmallow_sqlalchemy.ModelSchema
:
from marshmallow_sqlalchemy import ModelSchema
from my_alchemy_models import User
class UserSchema(ModelSchema):
class Meta:
model = User
同样适用于使用 flask_marshmallow.sqla.ModelSchema
。
Same applies to flask-sqlalchemy which uses flask_marshmallow.sqla.ModelSchema
.
对于普通的Python类,您可以一次定义字段并将其用于模式和模型/类:
In the case of vanilla Python classes, you may define the fields once and use it for both schema and model/class:
USER_FIELDS = ('name', 'email', 'created_at')
class User:
def __init__(self, name, email, created_at):
for field in USER_FIELDS:
setattr(self, field, locals()[field])
class UserSchema(Schema):
class Meta:
fields = USER_FIELDS
@post_load
def make_user(self, data):
return User(**data)
这篇关于使用棉花糖而不重复自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!