Here is a quote from docs:
Most web frameworks include infrastructure to establish a single
Session, associated with the request, which is correctly constructed
and torn down corresponding torn down at the end of a request. Such
infrastructure pieces include products such as Flask-SQLAlchemy, for
usage in conjunction with the Flask web framework, and
Zope-SQLAlchemy, for usage in conjunction with the Pyramid and Zope
frameworks. SQLAlchemy strongly recommends that these products be used
as available.
In those situations where integration libraries are not available,
SQLAlchemy includes its own “helper” class known as scoped_session.
So, looks like scoped_session is what you are talking about. Documentation on how to use scoped sessions is pretty good. Basically, you define when to open the session and when to close it (see Using Custom Created Scopes):
from my_web_framework import get_current_request, on_request_end
from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker(bind=some_engine), scopefunc=get_current_request)
@on_request_end
def remove_session(req):
Session.remove()
Hope that helps.