我使用Mixer作为SQLAlchemy模型的夹具生成器,烧瓶作为混合器后端。我有一个带有构造函数的User模型:
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), nullable=False, unique=True)
password = db.Column(db.String(64), nullable=False)
salt = db.Column(db.String(64), nullable=False)
def __init__(self, username, password):
# Stuff to init
pass
根据Mixer的文档,我创建了一个带有重写方法的Mixer子类,用构造函数参数填充模型,如下所示:
class MixerForModelsWithConstructor(Mixer):
"""
Mixer for models which requires constructor values
"""
def populate_target(self, values):
target = self.__scheme(**values)
return target
这就是我创建调音台装置的方法:
mixer = mixer = MixerForModelsWithConstructor(app=app)
user = mixer.blend(Users, username='test', password='test')
其中app
是Flask App对象。
但是,当我运行测试时,所有涉及的任务都会失败,因为模型构造函数仍然期望参数和Mixer没有传递它们。
非常感谢任何想法,提前谢谢。
答案 0 :(得分:0)
文档似乎已过时。
这是要使用的正确代码:
class CustomTypeMixer(TypeMixer):
def __init__(self, cls, mixer=None, factory=None, fake=True):
super().__init__(cls, mixer=mixer, factory=factory, fake=fake)
self.__scheme = cls # not sure why above line isn't setting this... is this the keyword 'cls' or just a variable named 'cls'?
def populate_target(self, values):
""" Populate a target by values. """
target = self.__scheme(**dict(values))
return target
class CustomMixer(Mixer):
type_mixer_cls = CustomTypeMixer
mixer = CustomMixer(session=session, commit=True)
从此答案https://github.com/klen/mixer/issues/12#issuecomment-409954829复制