For example, is there a difference between the following two?
session = Session() # Session is a session maker
try:
# do some work
session.commit()
except:
session.rollback()
finally:
session.close()
and
session = Session()
try:
# do some work
session.commit()
finally:
session.close()
The latter is what I used to do, because I assumed closing the session before committing (in case of an error) had the same effect as rolling back. But I saw the first form here.
Closing a session will implicitly roll back current transactional state:
The
close()
method issues aexpunge_all()
, and releases any transactional/connection resources. When connections are returned to the connection pool, transactional state is rolled back as well.
But I'd argue that the first form is still better, since explicit is better than implicit. The author of SQLAlchemy also seems to reflect this sentiment.
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