What's the recommended scoped_session usage pattern in a multithreaded sqlalchemy webapp?

Yes, this is the right way.

Example:

The Flask microframework with Flask-sqlalchemy extension does what you described. It also does .remove() automatically at the end of each HTTP request ("view" functions), so the session is released by the current thread. Calling just .commit() is not sufficient, you should use .remove().

When not using Flask views, I usually use a "with" statement:

@contextmanager
def get_db_session():
    try:
        yield session
    finally:
        session.remove()

with get_db_session() as session:
    # do something with session

You can create a similar decorator.

Scoped session creates a DBMS connection pool, so this approach will be faster than opening/closing session at each HTTP request. It also works nice with greenlets (gevent or eventlet).


You don't need to create a scoped session if you create new session for each request and each request is handled by single thread.

You have to call s.commit() to make pending objects persistent, i.e. to save changes into database.

You may also want to close session by calling s.close().