Package: mixer
TheMixeris a helper to generate instances of Django or SQLAlchemy models.
It’s useful for testing and fixture replacement. Fast and convenient test-data
generation.Mixer supports:Django;SQLAlchemy;Flask-SQLAlchemy;Peewee;Pony;Mongoengine;Marshmallow;Custom schemes;Docs are available at https://mixer.readthedocs.org/. Pull requests with
documentation enhancements and/or fixes are awesome and most welcome.Описание на русском языке:http://klen.github.io/mixer.htmlImportantFrom version 6.2 the Mixer library doesn’t support Python 2.
The latest version with python<3 support is mixer 6.1.3ContentsRequirementsInstallationUsageDjango workflowFlask, Flask-SQLAlchemySupport for Flask-SQLAlchemy models that have__init__argumentsSQLAlchemy workflowMongoengine workflowMarshmallow workflowCommon usageDB commitsCustom fieldsMiddlewaresLocalesBug trackerContributingContributorsLicenseRequirementsPython 3.7+Django (3.0, 3.1) for Django ORM support;Flask-SQLALchemy for SQLAlchemy ORM support and integration as Flask application;Faker >= 0.7.3Mongoengine for Mongoengine ODM support;SQLAlchemy for SQLAlchemy ORM support;Peewee ORM support;InstallationMixershould be installed using pip:pip install mixerUsageBy default Mixer tries to generate fake (human-friendly) data.If you want to randomize the generated values initialize the Mixerby manual: Mixer(fake=False)By default Mixer saves the generated objects in a database. If you want to disablethis, initialize the Mixer by manual like Mixer(commit=False)Django workflowQuick example:frommixer.backend.djangoimportmixerfromcustomapp.modelsimportUser,UserMessage# Generate a random useruser=mixer.blend(User)# Generate an UserMessagemessage=mixer.blend(UserMessage,user=user)# Generate an UserMessage and an User. Set username for generated user to 'testname'.message=mixer.blend(UserMessage,user__username='testname')# Generate SomeModel from SomeApp and select FK or M2M values from dbsome=mixer.blend('someapp.somemodel',somerelation=mixer.SELECT)# Generate SomeModel from SomeApp and force a value of money field from default to randomsome=mixer.blend('someapp.somemodel',money=mixer.RANDOM)# Generate SomeModel from SomeApp and skip the generation of money fieldsome=mixer.blend('someapp.somemodel',money=mixer.SKIP)# Generate 5 SomeModel's instances and take company field's values from custom generatorsome_models=mixer.cycle(5).blend('somemodel',company=(namefornameincompany_names))Flask, Flask-SQLAlchemyQuick example:frommixer.backend.flaskimportmixerfrommodelsimportUser,UserMessagemixer.init_app(self.app)# Generate a random useruser=mixer.blend(User)# Generate an userMessagemessage=mixer.blend(UserMessage,user=user)# Generate an UserMessage and an User. Set username for generated user to 'testname'.message=mixer.blend(UserMessage,user__username='testname')# Generate SomeModel and select FK or M2M values from dbsome=mixer.blend('project.models.SomeModel',somerelation=mixer.SELECT)# Generate SomeModel from SomeApp and force a value of money field from default to randomsome=mixer.blend('project.models.SomeModel',money=mixer.RANDOM)# Generate SomeModel from SomeApp and skip the generation of money fieldsome=mixer.blend('project.models.SomeModel',money=mixer.SKIP)# Generate 5 SomeModel's instances and take company field's values from custom generatorsome_models=mixer.cycle(5).blend('project.models.SomeModel',company=(companyforcompanyincompanies))Support for Flask-SQLAlchemy models that have__init__argumentsFor support this scheme, just create your own mixer class, like this:frommixer.backend.sqlalchemyimportMixerclassMyOwnMixer(Mixer):defpopulate_target(self,values):target=self.__scheme(**values)returntargetmixer=MyOwnMixer()SQLAlchemy workflowExample of initialization:frommixer.backend.sqlalchemyimportMixerENGINE=create_engine('sqlite:///:memory:')BASE=declarative_base()SESSION=sessionmaker(bind=ENGINE)mixer=Mixer(session=SESSION(),commit=True)role=mixer.blend('package.models.Role')Also, seeFlask,Flask-SQLAlchemy.Mongoengine workflowExample usage:frommixer.backend.mongoengineimportmixerclassUser(Document):created_at=DateTimeField(default=datetime.datetime.now)email=EmailField(required=True)first_name=StringField(max_length=50)last_name=StringField(max_length=50)username=StringField(max_length=50)classPost(Document):title=StringField(max_length=120,required=True)author=ReferenceField(User)tags=ListField(StringField(max_length=30))post=mixer.blend(Post,author__username='foo')Marshmallow workflowExample usage:frommixer.backend.marshmallowimportmixerimportmarshmallowasmaclassUser(ma.Schema):created_at=ma.fields.DateTime(required=True)email=ma.fields.Email(required=True)first_name=ma.fields.String(required=True)last_name=ma.fields.String(required=True)username=ma.fields.String(required=True)classPost(ma.Schema):title=ma.fields.String(required=True)author=ma.fields.Nested(User,required=True)post=mixer.blend(Post,author__username='foo')Common usageQuick example:frommixer.mainimportmixerclassTest:one=inttwo=intname=strclassScheme:name=strmoney=intmale=boolprop=Testscheme=mixer.blend(Scheme,prop__one=1)DB commitsBy default ‘django’, ‘flask’, ‘mongoengine’ backends tries to save objects in
database. For preventing this behavior initmixermanually:frommixer.backend.djangoimportMixermixer=Mixer(commit=False)Or you can temporary switch context use the mixer as context manager:frommixer.backend.djangoimportmixer# Will be save to dbuser1=mixer.blend('auth.user')# Will not be save to dbwithmixer.ctx(commit=False):user2=mixer.blend('auth.user')Custom fieldsThe mixer allows you to define generators for fields by manually.
Quick example:frommixer.mainimportmixerclassTest:id=intname=strmixer.register(Test,name=lambda:'John',id=lambda:str(mixer.faker.small_positive_integer()))test=mixer.blend(Test)test.name=='John'isinstance(test.id,str)# You could pinned just a value to fieldmixer.register(Test,name='Just John')test=mixer.blend(Test)test.name=='Just John'Also, you can make your own factory for field types:frommixer.backend.djangoimportMixer,GenFactorydefget_func(*args,**kwargs):return"Always same"classMyFactory(GenFactory):generators={models.CharField:get_func}mixer=Mixer(factory=MyFactory)MiddlewaresYou can add middleware layers to process generation:frommixer.backend.djangoimportmixer# Register middleware to model@mixer.middleware('auth.user')defencrypt_password(user):user.set_password('test')returnuserYou can add several middlewares. Each middleware should get one argument
(generated value) and return them.It’s also possible to unregister a middleware:mixer.unregister_middleware(encrypt_password)LocalesBy default mixer uses ‘en’ locale. You could switch mixer default locale by
creating your own mixer:frommixer.backend.djangoimportMixermixer=Mixer(locale='it')mixer.faker.name()## u'Acchisio Conte'At any time you could switch mixer current locale:mixer.faker.locale='cz'mixer.faker.name()## u'Miloslava Urbanov\xe1 CSc.'mixer.faker.locale='en'mixer.faker.name()## u'John Black'# Use the mixer context managermixer.faker.phone()## u'1-438-238-1116'withmixer.ctx(locale='fr'):mixer.faker.phone()## u'08 64 92 11 79'mixer.faker.phone()## u'1-438-238-1116'Bug trackerIf you have any suggestions, bug reports or
annoyances please report them to the issue tracker
athttps://github.com/klen/mixer/issuesContributingDevelopment of mixer happens at Github:https://github.com/klen/mixerContributorsAntoine Bertin            (https://github.com/Diaoul)Benjamin Port             (https://github.com/bport)Dmitriy Moseev            (https://github.com/DmitriyMoseev)Eelke Hermens             (https://github.com/eelkeh)Esteban J. G. Gabancho    (https://github.com/egabancho)Felix Dreissig            (https://github.com/F30)Illia Volochii            (https://github.com/illia-v)Jannis                    (https://github.com/jnns)Kirill Pavlov             (https://github.com/pavlov99)Kwok-kuen Cheung          (https://github.com/cheungpat)Mahdi Yusuf               (https://github.com/myusuf3)Marek Baczyński           (https://github.com/imbaczek)Marigold                  (https://github.com/Marigold)Matt Caldwell             (https://github.com/mattcaldwell)Mikhail Porokhovnichenko  (https://github.com/marazmiki)Skylar Saveland           (https://github.com/skyl)Suriya Subramanian        (https://github.com/suriya)Gram                      (https://github.com/orsinium)Joshua                    (https://github.com/jomasti)Lucas Rangel Cezimbra     (https://github.com/lucasrcezimbra)avi-pomicell              (https://github.com/avi-pomicell)Jochen Brissier           (https://github.com/jbrissier)LicenseLicensed under aBSD license.