Close sqlalchemy session after app close

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

@st.experimental_singleton
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.configure(expire_on_commit=False)
session = Session()
Base.metadata.create_all(bind=engine)
_ = 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:
run_streamlit_core_app()

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?

Thanks,

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.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.