database.py 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. from . import settings
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.orm import sessionmaker
  4. from sqlalchemy.orm import scoped_session
  5. # The SQLAlchemy "Engine" is the "starting point" for using SQLAlchemy. In this
  6. # plugin we do not reuse the Pagure database session, because we're using a
  7. # separate database (we do not create new tables in the Pagure database in
  8. # order to keep the plugin completely separate). A new session for querying the
  9. # database is started at the beginning of every incoming HTTP request, or when
  10. # a Celery task is ran.
  11. #
  12. # Useful documentation for SQLAlchemy to understand how the plugin is set up:
  13. # https://docs.sqlalchemy.org/en/13/orm/contextual.html
  14. engine = create_engine(settings.DB_URL, echo=True, pool_recycle=3600)
  15. def start_database_session():
  16. """
  17. Get a new SQLAlchemy work session. The Session object is used to query the
  18. database. To end a session simply call .remove() on the session object that
  19. is returned from this function.
  20. sessionmaker() is a SQLAlchemy session factory.
  21. scoped_session() is a SQLAlchemy registry of session objects. By
  22. using this registry, if somewhere else in the same request were
  23. to create a new session, the *same* object will be returned instead
  24. of starting a new one. Sessions are thread-local (2 different flask
  25. requests will start different sessions).
  26. """
  27. return scoped_session(sessionmaker(bind=engine))