Search code examples
pythontransactionssqlalchemycontextmanager

how to automate manage transactions in SQL Alchemy


When use java Hibernate & Spring framework, there is a transaction manager which we can configure some transaction rules, then we don't need write "commit, flush, rollback" stuff each time.


Solution

  • For python SQL Alchemy, we can use decorators and context managers to manage transactions(official sample from doc):

    from contextlib import contextmanager
    
    @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()
    
    
    def run_my_program():
        with session_scope() as session:
            ThingOne().go(session)
            ThingTwo().go(session)
    

    an transactions library is also a good choice to do that.