Last active
July 5, 2022 19:28
-
-
Save fitzy1321/93e7afc7a7b8b960cd9963e4bd6d1762 to your computer and use it in GitHub Desktop.
SQLAlchemy scoped_session contextmanager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
from typing import Generator | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import Session, scoped_session, sessionmaker | |
@contextmanager | |
def scoped_session_maker( | |
db_conn: str, | |
pool_size: int = 2, | |
) -> Generator[Session, None, None]: | |
""" | |
SQLAlchemy scoped_session context manager, for thread safe session management. | |
Example: | |
with scoped_session_maker("sqlite://") as session: | |
result = session.query(Model).one() | |
""" | |
# engine and or sessionmaker could be passed in | |
# but for the sake of clarity, they're fine here. | |
engine = create_engine(db_conn, pool_size=pool_size) | |
sc_session = scoped_session(sessionmaker(engine)) | |
session = sc_session() | |
try: | |
yield session | |
session.commit() | |
except Exception: | |
session.rollback() | |
raise | |
finally: | |
sc_session.remove() | |
engine.dispose() # may or not be needed. docs not clear |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment