I am trying to figure out the preferred way to manage session if exceptiion occurs while doing operation or committing the session. But a few examples in the document confuses me a little bit.
The doc says to frame out a commit/rollback block, you can do something like this:
# verbose version of what a context manager will do
with Session(engine) as session:
session.begin()
try:
session.add(some_object)
session.add(some_other_object)
except:
session.rollback()
raise
else:
session.commit()
While this example includes the commit()
call in the try
block:
Session = sessionmaker(bind=engine)
session = Session()
session.begin()
try:
item1 = session.query(Item).get(1)
item2 = session.query(Item).get(2)
item1.foo = 'bar'
item2.bar = 'foo'
session.commit()
except:
session.rollback()
raise
I wonder:
session.begin()
context manager, so does it handle the exception occurs while commit()
?Possible related answes:
Here is a answer that exludes commit()
from the try
block, but the explanation in the comments doesn't seem sufficient to me.
And this answer mentions about why including commit()
in try
block.
Both examples accomplish nearly the same thing. The transaction will be committed if there is no error, and rolled back if there is an error.
The difference is that if there is an exception on the commit itself, the second example will roll back. It's uncommon to get an exception on the commit, but it's possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With