Close sqlalchemy session after app close

I follow the guide here to create my connection to database
Connect Streamlit to PostgreSQL - Streamlit Docs

def db_connection():
“”“connect to the postgresql using sqlalchemy orm to control eng’s virtual machine”“”
conn_str = “postgresql+psycopg2://connect-string-here”
engine = sa.create_engine(conn_str, future=True, echo=False, pool_recycle=3600)
Session = sessionmaker(bind=engine)
session = Session()
_ = session.connection()
return session, engine

I want to close the session and the engine when the user close the app.
As suggested on sqlalchemy

if I do
with engine.begin() as conn:

The core app has callback functions. The connection will be closed when the app finished loading.
How do I trigger a teardown function when users close the tab?


Hi @danielairy,

Thanks so much for posting! Please check out our new guidelines for posting in the forum and update your post to properly format your code snippet.