Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

Overview

https://raw.github.com/klen/mixer/develop/docs/_static/logo.png

The Mixer is 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:

Tests Status Version Downloads License

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.html

Important

From version 6.2 the Mixer library doesn't support Python 2. The latest version with python<3 support is mixer 6.1.3

Requirements

  • Python 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.3
  • Mongoengine for Mongoengine ODM support;
  • SQLAlchemy for SQLAlchemy ORM support;
  • Peewee ORM support;

Installation

Mixer should be installed using pip:

pip install mixer

Usage

By default Mixer tries to generate fake (human-friendly) data.
If you want to randomize the generated values initialize the Mixer
by manual: Mixer(fake=False)
By default Mixer saves the generated objects in a database. If you want to disable
this, initialize the Mixer by manual like Mixer(commit=False)

Django workflow

Quick example:

from mixer.backend.django import mixer
from customapp.models import User, UserMessage

# Generate a random user
user = mixer.blend(User)

# Generate an UserMessage
message = 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 db
some = mixer.blend('someapp.somemodel', somerelation=mixer.SELECT)

# Generate SomeModel from SomeApp and force a value of money field from default to random
some = mixer.blend('someapp.somemodel', money=mixer.RANDOM)

# Generate 5 SomeModel's instances and take company field's values from custom generator
some_models = mixer.cycle(5).blend('somemodel', company=(name for name in company_names))

Flask, Flask-SQLAlchemy

Quick example:

from mixer.backend.flask import mixer
from models import User, UserMessage

mixer.init_app(self.app)

# Generate a random user
user = mixer.blend(User)

# Generate an userMessage
message = 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 db
some = mixer.blend('project.models.SomeModel', somerelation=mixer.SELECT)

# Generate SomeModel from SomeApp and force a value of money field from default to random
some = mixer.blend('project.models.SomeModel', money=mixer.RANDOM)

# Generate 5 SomeModel's instances and take company field's values from custom generator
some_models = mixer.cycle(5).blend('project.models.SomeModel', company=(company for company in companies))

Support for Flask-SQLAlchemy models that have __init__ arguments

For support this scheme, just create your own mixer class, like this:

from mixer.backend.sqlalchemy import Mixer

class MyOwnMixer(Mixer):

    def populate_target(self, values):
        target = self.__scheme(**values)
        return target

mixer = MyOwnMixer()

SQLAlchemy workflow

Example of initialization:

from mixer.backend.sqlalchemy import Mixer

ENGINE = create_engine('sqlite:///:memory:')
BASE = declarative_base()
SESSION = sessionmaker(bind=ENGINE)

mixer = Mixer(session=SESSION(), commit=True)
role = mixer.blend('package.models.Role')

Also, see Flask, Flask-SQLAlchemy.

Mongoengine workflow

Example usage:

from mixer.backend.mongoengine import mixer

class User(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)

class Post(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 workflow

Example usage:

from mixer.backend.marshmallow import mixer
import marshmallow as ma

class User(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)

class Post(ma.Schema):
    title = ma.fields.String(required=True)
    author = ma.fields.Nested(User, required=True)

post = mixer.blend(Post, author__username='foo')

Common usage

Quick example:

from mixer.main import mixer

class Test:
    one = int
    two = int
    name = str

class Scheme:
    name = str
    money = int
    male = bool
    prop = Test

scheme = mixer.blend(Scheme, prop__one=1)

DB commits

By default 'django', 'flask', 'mongoengine' backends tries to save objects in database. For preventing this behavior init mixer manually:

from mixer.backend.django import Mixer

mixer = Mixer(commit=False)

Or you can temporary switch context use the mixer as context manager:

from mixer.backend.django import mixer

# Will be save to db
user1 = mixer.blend('auth.user')

# Will not be save to db
with mixer.ctx(commit=False):
    user2 = mixer.blend('auth.user')

Custom fields

The mixer allows you to define generators for fields by manually. Quick example:

from mixer.main import mixer

class Test:
    id = int
    name = str

mixer.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 field
mixer.register(Test, name='Just John')
test = mixer.blend(Test)
test.name == 'Just John'

Also, you can make your own factory for field types:

from mixer.backend.django import Mixer, GenFactory

def get_func(*args, **kwargs):
    return "Always same"

class MyFactory(GenFactory):
    generators = {
        models.CharField: get_func
    }

mixer = Mixer(factory=MyFactory)

Middlewares

You can add middleware layers to process generation:

from mixer.backend.django import mixer

# Register middleware to model
@mixer.middleware('auth.user')
def encrypt_password(user):
    user.set_password('test')
    return user

You 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)

Locales

By default mixer uses 'en' locale. You could switch mixer default locale by creating your own mixer:

from mixer.backend.django import Mixer

mixer = 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 manager
mixer.faker.phone()         ## u'1-438-238-1116'
with mixer.ctx(locale='fr'):
    mixer.faker.phone()     ## u'08 64 92 11 79'

mixer.faker.phone()         ## u'1-438-238-1116'

Bug tracker

If you have any suggestions, bug reports or annoyances please report them to the issue tracker at https://github.com/klen/mixer/issues

Contributing

Development of mixer happens at Github: https://github.com/klen/mixer

Contributors

License

Licensed under a BSD license.

Owner
Kirill Klenov
Kirill Klenov
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication. For use with cookiecutter.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

4.3k Dec 29, 2022
Small and simple gravatar usage in Flask.

Flask Gravatar About This is small and simple integration gravatar into flask. Installation Flask-Gravatar is on PyPI so all you need is: pip install

Alexander Zelenyak 78 Sep 15, 2022
Implement Instagram with flask

Blue club The place where manly men live and breathe. Move to Notion Move to Fig

3 Apr 07, 2022
Library books management program, built with Flask, Python

Library books management program, With many features and good User Interface. built with Flask, Python. (Include Screenshots) and documentation on how to run it! Thank you :)

Thierry Mugisha 1 May 03, 2022
retorna informações de pessoas que não existem

random-person-api API que entrega dados aleatórios sobre pessoas que (provavelmente) não existem. Como usar? Copie o link abaixo https://random-person

Miguel 3 Aug 09, 2022
REST API with mongoDB and Flask.

Flask REST API with mongoDB py 3.10 First, to install all dependencies: python -m pip install -r requirements.txt Second, into the ./src/ folder, cop

Luis Quiñones Requelme 3 Mar 05, 2022
A simple application builder. Made with python.

Python Flask Server Template Check the Github Repository for updates Flask is an application builder. It is very common in Python but can also be used

1 Jan 09, 2022
Rubik's cube assistant on Flask webapp

webcube Rubik's cube assistant on Flask webapp. This webapp accepts the six faces of your cube and gives you the voice instructions as a response. Req

Yash Indane 56 Nov 22, 2022
Search users in Github. Created with Flask, PipEnv, Heroku and free time.

Search in Github Here search for users in Github and other stuff! This app is working with, Data Github API BackEnd Flask Language Python Package mana

AmirHossein Mohammadi 12 Jan 16, 2022
i18n and l10n support for Flask based on Babel and pytz

Flask Babel Implements i18n and l10n support for Flask. This is based on the Python babel module as well as pytz both of which are installed automatic

397 Dec 15, 2022
SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).

Flask-SeaSurf SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF). CSRF vulnerabilities have been found in large and popular

Max Countryman 183 Dec 28, 2022
This is a simple web application using Python Flask and MySQL database.

Simple Web Application This is a simple web application using Python Flask and MySQL database. This is used in the demonstration of development of Ans

Alaaddin Tarhan 1 Nov 16, 2021
Intranet de la Rez Flask web app

IntraRez Application Flask de l'Intranet de la Rez. Exigences Python : Probablement = 3.10 à terme, pour l'instant = 3.8 suffit ; Autres packages Li

3 Jul 03, 2022
REST API built using flask framework that used for managing bookmarks by individual users.

Bookmarks REST API REST API built using flask framework that used for managing bookmarks by individual users. API Consumers Note This app is built usi

Venkatesh Tantravahi 1 Dec 27, 2021
Flask Apps - Open-Source And Paid | AppSeed

Flask Apps Open-Source web apps built with automation tools, HTML parsing and boilerplated code in Flask - - Provided by AppSeed App Generator. What i

App Generator 120 Oct 04, 2022
Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications.

Flask Sitemapper Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications. This allows you to create a nice and

6 Jan 06, 2023
A basic CRUD application built in flask using postgres as database

flask-postgres-CRUD A basic CRUD application built in flask using postgres as database Taks list Dockerfile Initial docker-compose - It is working Dat

Pablo Emídio S.S 9 Sep 25, 2022
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

249 Jan 06, 2023
A swagger 2.0 spec extractor for flask

flask-swagger A Swagger 2.0 spec extractor for Flask You can now specify base path for yml files: app = Flask(__name__) @app.route("/spec") def spec(

Sling 457 Dec 02, 2022
A Flask application for Subdomain Enumeration

subdomainer-flask A Flask application for Subdomain Enumeration steps to be done git clone https://github.com/gokulapap/subdomainer-flask pip3 install

GOKUL A.P 7 Sep 22, 2022