Pattern
I usually have this kind of pattern when working with sqlalchemy:
session = get_the_session_one_way_or_another()
try: # do something with the session except: # * see comment below session.rollback() raise else: session.commit() To make things easier to use, it is useful to have this as a context manager:
@contextmanager def get_session(): session = get_the_session_one_way_or_another()
try:
yield session
except:
session.rollback()
raise
else:
session.commit()
And then:
with get_session() as session: # do something with the session
https://stackoverflow.com/questions/52232979/sqlalchemy-rollback-when-exception