python 26 lines · 6 steps

Scoped SQLAlchemy sessions in Flask

Wire a thread-local database session into Flask so each request gets a clean session that commits or rolls back automatically.

Explained by highlit
1from flask import Flask, g, current_app
2from sqlalchemy import create_engine
3from sqlalchemy.orm import scoped_session, sessionmaker
4 
5app = Flask(__name__)
6app.config["DATABASE_URL"] = "postgresql://localhost/app"
7 
8engine = create_engine(app.config["DATABASE_URL"], pool_pre_ping=True)
9SessionFactory = sessionmaker(bind=engine, expire_on_commit=False)
10db_session = scoped_session(SessionFactory)
11 
12 
13@app.teardown_appcontext
14def shutdown_session(exception=None):
15 session = db_session()
16 try:
17 if exception is not None:
18 session.rollback()
19 elif session.in_transaction():
20 session.commit()
21 except Exception:
22 session.rollback()
23 current_app.logger.exception("Failed to finalize database session")
24 raise
25 finally:
26 db_session.remove()
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A scoped_session gives every thread or request its own session while sharing one connection pool.
  2. 2Deciding commit-versus-rollback based on whether an exception occurred keeps writes atomic per request.
  3. 3Always removing the session in a finally block prevents leaked connections and stale state across requests.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Scoped SQLAlchemy sessions in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code