Paul's Programming Notes PostsRSSGithub

Do I need to use SQLAlchemy's scoped_session?

If your application has the potential to run in multiple threads, then you absolutely should use scoped_session. A Session isn’t safe to share across threads, and scoped_session makes sure each thread gets its own.

from sqlalchemy.orm import scoped_session, sessionmaker

Session = scoped_session(sessionmaker(bind=engine))

session = Session()  # the same session everywhere in this thread

It’s a registry keyed on the current thread by default. Every call to Session() from the same thread hands back the same object, so you can get at the session deep inside a function without threading one down through every caller, and another thread gets its own instead of stepping on yours.

You do have to call Session.remove() when the unit of work is finished, otherwise the session stays in the registry along with every object in its identity map. Web frameworks usually hook that into the end of a request. Flask-SQLAlchemy sets all of this up for you, so if you’re using that you already have a scoped session.

If your application is single threaded and you’re already passing one session around explicitly, you don’t need it.