flask.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """ Module integrate the Mixer to Flask application.
  2. See example: ::
  3. from mixer.backend.flask import mixer
  4. mixer.init_app(flask_app)
  5. user = mixer.blend('path.to.models.User')
  6. """
  7. from __future__ import absolute_import
  8. from .sqlalchemy import TypeMixer, Mixer as BaseMixer
  9. class Mixer(BaseMixer):
  10. """ Init application. """
  11. type_mixer_cls = TypeMixer
  12. def __init__(self, app=None, commit=True, **kwargs):
  13. """ Initialize the SQLAlchemy Mixer.
  14. :param fake: (True) Generate fake data instead of random data.
  15. :param app: Flask application
  16. :param commit: (True) Commit instance to session after creation.
  17. """
  18. super(Mixer, self).__init__(**kwargs)
  19. self.params['commit'] = commit
  20. if app:
  21. self.init_app(app)
  22. def init_app(self, app):
  23. """ Init application.
  24. This callback can be used to initialize an application for the
  25. use with this mixer setup.
  26. :param app: Flask application
  27. """
  28. assert app.extensions and app.extensions[
  29. 'sqlalchemy'], "Flask-SQLAlchemy must be inialized before Mixer."
  30. db = app.extensions['sqlalchemy'].db
  31. self.params['session'] = db.session
  32. # register extension with app
  33. app.extensions['mixer'] = self
  34. # Default mixer
  35. mixer = Mixer(commit=True)
  36. # lint_ignore=W0201