On 16/11/2018 01:09, Mike Bayer wrote:
Does SQLAlchemy provide a context manager that handles the session
lifecycle described here?
https://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#managing-transactions
I mean, it should be as simple as the following, right?
@contextmanager
def transaction(session):
session.begin()
try:
yield
session.commit()
except:
session.rollback()
raise
finally:
session.close()
...I'd just prefer not to copy and paste that across libraries and
projects ;-)
I guess that documentation should be updated, that yes that workflow
is available, it's documented in terms of using "begin()" with
autocommit mode:
https://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#session-autocommit
That chunk is a little confusing, I wish there was a (default) mode that
said "start a transaction when I ask for one, don't have one open
otherwise" - "idle in transaction" does make Postgres DBAs sad...
I see your example also uses begin(), but that's not what we have at
https://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#managing-transactions,
Right, I guess my knowledge of begin() is hazier than I thought...
that's a Session without the begin() as it's not in autocommit.
Which I don't want people to use :)
I don't want autocommit, but I do want an explicit start and end of
transaction, and indeed, session, particularly in my current project as
all the SQLA stuff has to be done in a twisted deferToThread ;-)
So....at the moment you can still say this:
with session.transaction:
which will do the commit and rollback but not the close().
Potentially silly question: when is it useful to commit the session but
not close it?
there's kind of too many options with the Session right now to make
this one size fits all unless you have suggestions.
Indeed, would you believe after almost 10 years, I think sessionmaker()
finally made sense to my brain?
cheers,
Chris
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.