Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JoshCrosby/30c1b950d8f2bb9cd6d5fa894af10cda to your computer and use it in GitHub Desktop.
Save JoshCrosby/30c1b950d8f2bb9cd6d5fa894af10cda to your computer and use it in GitHub Desktop.
SQLAlchemy Session Context Manager
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(bind=engine)
SessionMaker = sessionmaker(bind=engine)
@contextmanager
def session_manager():
"""
example :
with session_manager() as session:
result = session.query(User).all()
print(result)
"""
session = SessionMaker()
try:
yield session
except Exception as e:
print("rollback transaction")
session.rollback()
raise
finally:
print("closing connection")
session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment