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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A scoped_session gives every thread or request its own session while sharing one connection pool.
- 2Deciding commit-versus-rollback based on whether an exception occurred keeps writes atomic per request.
- 3Always removing the session in a finally block prevents leaked connections and stale state across requests.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/scoped-sqlalchemy-sessions-in-flask-explained-python-3d57/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.