Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Sessions and Transactions

Session Patterns: sessionmaker, scoped_session and Events

Create sessions the right way with sessionmaker, use scoped_session safely, build a request-scoped session helper, and hook into flushes with ORM events for audit fields.

A real application creates thousands of sessions. You need one consistent place that makes them, a rule for how long each lives, and sometimes a way to run code automatically when objects are saved (set a timestamp, write an audit row). This lesson covers the standard tools for all three.

sessionmaker: a session factory

sessionmaker is configured once, usually at import time, and then called like a function whenever you need a session. It carries the engine and any session options.

Python sessionmaker as a factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use SessionLocal() as a context manager for reads and SessionLocal.begin() for writes. Everything configured on the factory (expire_on_commit, autoflush, bind) applies to every session it makes.

How long should a session live?

The rule of thumb: one session per unit of work. In a web app that is one request. In a worker it is one job. In a script it is one logical operation. Not one per query, and not one per process.

  • Too short (a session per query) loses the identity map and makes lazy loading fail on detached objects.
  • Too long (a global session) keeps connections and stale objects around and is unsafe across threads or async tasks.

A request-scoped helper is the standard pattern. The generator below is what frameworks call a dependency: it opens a session, yields it, and closes it even when the handler fails.

Python A request-scoped session helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same shape works as a FastAPI Depends, a Flask teardown_appcontext function, or a Celery task wrapper.

scoped_session: a registry of one session per thread

scoped_session(SessionLocal) returns a registry object. Calling Session() returns the same session for the current scope (by default, the current thread), and Session.remove() closes it and forgets it. Flask-SQLAlchemy uses this pattern, and many older code bases do too.

Python scoped_session returns the same session per scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Prefer an explicit with SessionLocal() as session: and pass the session down as an argument. scoped_session hides a global, which makes tests harder and breaks in async code unless you give it a scope function (for example scopefunc=asyncio.current_task for the async variants). Reach for it only when a framework or an existing code base needs it.

ORM events

The session and mappers emit events you can listen to. They are how you add behavior that should happen for every object of a kind, without repeating it at each call site.

Event Fires Typical use
before_insert / before_update (mapper) per object, during flush set timestamps, normalize values
after_insert / after_update after the row is written write audit rows, invalidate cache
before_flush (session) before the flush plans its work inspect session.new, .dirty, .deleted
after_commit / after_rollback when the transaction ends publish messages only after success
set (attribute) when an attribute changes validation, derived values

Mapper events happen inside the flush: do not use the session inside them to add or modify ORM objects. Use before_flush for that, or restrict yourself to changing the object's own columns.

Python Automatic created_at / updated_at with events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For this particular job you can also let the database do it with server_default=func.now() and onupdate=func.now() on the column. Events are the better tool for logic the database cannot express.

Session events: inspect everything about to be saved

before_flush gives you the whole picture of pending changes, which makes cross-cutting features easy. This example counts what each flush will do:

Python before_flush as an audit log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep event handlers small and fast. They run for every object, and hidden behavior is hard to debug, so document each listener where the model is defined.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a sessionmaker?

    sessionmaker stores the engine and session options and creates a new Session each time you call it.
  2. 2. What is the recommended lifetime of a session in a web application?

    A session per unit of work keeps the identity map small and connections short-lived.
  3. 3. What does Session.remove() do on a scoped_session?

    remove() closes the session for the current scope and discards it.
  4. 4. Where should you add or modify other ORM objects in response to a flush?

    Mapper-level flush events must not use the session to change ORM state; before_flush is designed for that.

Summary

  • Create sessionmaker once and call it for every unit of work; SessionLocal.begin() commits on success.
  • One session per request or job; always close it, and roll back on errors.
  • scoped_session returns one session per thread or scope; prefer explicit sessions when you can.
  • ORM events (before_insert, before_flush, after_commit, attribute set) add behavior that applies to every object.
  • Keep listeners small, and use before_flush when a handler needs to change other ORM objects.

Next: Alembic: Your First Migrations