try: <use session> session.commit() except: session.rollback() raise finally: session.close() # optional, depends on use case