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

11 views
Skip to first unread message

Petr Blahoš

unread,
Sep 1, 2021, 6:53:55 AM9/1/21
to pylons-...@googlegroups.com
Hi,

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):
session.close()
request.add_finished_callback(cleanup)
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()
zope.sqlalchemy.register(session, transaction_manager=request.tm)
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?

Thanks...
Petr
--

Michael Merickel

unread,
Sep 1, 2021, 12:30:26 PM9/1/21
to pylons-...@googlegroups.com
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 request.tm and use it (via zope.sqlalchemy or other using request.tm 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 pylons-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pylons-discuss/CA%2ByMeXWHgTrt%3DTHkK-fgAcdjxxpqe3nQkuy1RBg4ziM61Axazg%40mail.gmail.com.

Theron Luhn

unread,
Sep 1, 2021, 1:19:56 PM9/1/21
to pylons-...@googlegroups.com
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
Forward
0 new messages