2

I understand that with the standard MySQLdb driver, you usually use a with statement to ensure that the connection is closed with __exit__.

Is there an equivalent with statement that I need for SQLAlchemy sessions or maybe the engine? Or is the manual timeout to close connections sufficient for SQLAlchemy?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The phrase you are looking for is a "context manager", which is an object that adheres to the attribute naming convention needed to be used in a with statement. See "Working with the Engine" in the docs for working with a context manager for engine connections:

with engine.begin() as connection:
    r1 = connection.execute(table1.select())
    connection.execute(table1.insert(), col1=7, col2='this is some data')

As best as I can tell, there is no such functionality for a Session object itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.