Hi all,
I'm having trouble understanding how to use
session.begin(subtransactions=True) as a context manager. I'm working in
Python 2.7.5 with SQLAlchemy 1.1.14 in a Flask 0.12.2 application on CentOS
7 servers. I like session.begin() as a context manager, but things aren't
working as I thought they would. For example:
with db.session.begin(subtransactions=True):
# create a model instance
thing = Thing(...)
db.session.add(thing)
I thought when the context manager went out of scope it would perform a
db.session.commit() to persist the thing instance, but I haven't seen
changes to the database. But if I change the code to this:
with db.session.begin(subtransactions=True):
# create a model instance
thing = Thing(...)
db.session.add(thing)
db.session.commit()
it raises a ResourceClosedError: This transaction is closed
What works for me is this:
with db.session.begin(subtransactions=True):
# create a model instance
thing = Thing(...)
db.session.add(thing)
db.session.commit()
Where the commit() is outside the scope of the context manager. But this
seems contrary to me, and makes me think I'm doing something wrong as my
expectation of what
with db.session.begin(...)
does is this (pseudocode):
begin transaction
try:
create some model instance
add them to the session
commit handled by leaving the scope of the context manager
except
rollback on exception
It would be very much appreciated is someone could point me in the right
direction, give me some suggestions or references about what I'm missing.
Thanks,
Doug
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.