session.close() no longer needed or even never needed?

Skip to first unread message

Petr Blahoš

Sep 1, 2021, 6:53:55 AM9/1/21

I am upgrading some old code of mine, and I came across the
request.db (I think it's called request.session in Pyramid scaffolding)
method which looks like:

def db(request):
session = request.registry.sessionmaker()

def cleanup(request):
return session

and calling config.add_request_method(db, reify=True) somewhere, while the sessionmaker was called with ZopeTransactionExtension.

The "current" version is something like:
def db(request):
session = request.registry.sessionmaker()
return session

Now, I wonder. I expect that pyramid_tm takes care of the cleanup / session.close()
for the request. But I have always used the transaction manager pyramid_tm. Am I 
guessing correctly, that adding finished callback(cleanup) was unnecessary?


Michael Merickel

Sep 1, 2021, 12:30:26 PM9/1/21
Unfortunately there's no "right" answer to the situation, it all depends on how you choose to manage database connections in your app.

It's hard to answer whether what you're doing now is correct or not without knowing more - you can have pyramid_tm enabled in your app and not actually use it. It'll just be a no-op if things don't hook into and use it (via zope.sqlalchemy or other using directly).

The cookiecutter provides what I'd consider to be the best option (but I'm biased) which sets up pyramid_tm to manage the begin/commit on the transaction. However there are perfectly legitimate ways to handle things (such as in your first example) that do not use pyramid_tm with zope.sqlalchemy.

- Michael

You received this message because you are subscribed to the Google Groups "pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

Theron Luhn

Sep 1, 2021, 1:19:56 PM9/1/21
I would very strongly recommend against the first example, using request.add_finished_callback to close the session.  add_finished_callback is outside main request stack (tweens and view derivers and all that), where the error handling tends to be.  Speaking from experience, I was completely ignorant of a whole plethora of errors in my app because session errors weren’t being captured.

— Theron

Reply all
Reply to author
0 new messages