0

I have created a context manager to get a transactional session, following the instructions here:

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = Session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

And it's working great. Now I'd like to do something like that but for sessions that I know are only used to fetch values from the database.

Instead of session.commit(), what would be the best thing to do with the session? Just .rollback() and that's it?

Savir
  • 17,568
  • 15
  • 82
  • 136
  • 2
    Why not just `session.close()`? – benvc Apr 30 '19 at 15:18
  • 2
    @benvc zzzeek has expressed that one should preferrably always explicitly either commit or rollback instead of just closing and trusting in the implicit rollback: https://stackoverflow.com/questions/17008441/why-do-sqlalchemy-session-close-not-log-rollback – Ilja Everilä May 01 '19 at 07:28
  • @IljaEverilä - thanks for the reference. Makes sense from a bulletproofing perspective, here is another post that I found useful on the subject: https://stackoverflow.com/questions/309834/should-i-commit-or-rollback-a-read-transaction – benvc May 01 '19 at 13:10

0 Answers0