database.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2017 Tomek Wójcik <tomek@bthlabs.pl>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. # THE SOFTWARE.
  21. #
  22. """
  23. q3stats.database
  24. ================
  25. This module contains database utilities.
  26. """
  27. import sqlalchemy as sa
  28. from sqlalchemy.ext.declarative import declarative_base
  29. #: Base for declarative models
  30. Base = declarative_base()
  31. #: Current SQLAlchemy engine
  32. db_engine = None
  33. #: Current SQLAlchemy session
  34. db_session = None
  35. def create_engine(config):
  36. """Creates and initializes engine according to *config* dictionary.
  37. Returns the initialized engine."""
  38. engine = sa.create_engine(
  39. config['SQLALCHEMY_URL'], **config.get('SQLALCHEMY_OPTS', {})
  40. )
  41. return engine
  42. def create_session(engine, config, scoped=True):
  43. """Creates a session factory bound to *engine* according to *config*
  44. dictionary. If *scoped* is ``True`` then the session will be scoped.
  45. Otherwise, it'll be a standard ``sessionmaker``.
  46. Returns the initialized session factory."""
  47. Session = sa.orm.sessionmaker(
  48. bind=engine, **config.get('SQLALCHEMY_SESSION_OPTS', {})
  49. )
  50. if scoped:
  51. return sa.orm.scoped_session(Session)
  52. return Session