如何在SQLAlchemy中使用带有作用域会话的嵌套事务?

时间:2012-11-11 10:18:20

标签: python transactions python-2.7 sqlalchemy

我已经在我的应用程序中编写了用于处理嵌套事务的代码。但是当它回滚一次之后,所有事务都会回滚直到我重新启动应用程序。

# method_a starts a transaction and calls method_b
def method_a():
    session.begin(subtransactions=True)
    try:
        method_b()
        session.commit()  # transaction is committed here
    except:
        session.rollback() # rolls back the transaction


# method_b also starts a transaction, but when
# called from method_a participates in the ongoing
# transaction.
def method_b():
    session.begin(subtransactions=True)
    try:
        session.add(SomeObject('bat', 'lala'))
        session.commit()  # transaction is not committed yet
    except:
        session.rollback() # rolls back the transaction, in this case
                       # the one that was initiated in method_a().


# create a Session and call method_a
session = Session(autocommit=True)
global session
method_a(session)

1 个答案:

答案 0 :(得分:3)

除非使用SAVEPOINT,否则session.rollback()会回滚整个事务,无论是否嵌套。嵌套“子事务”的目的是使得几个代码块可以分别指定它们“begin()”和“commit()”事务,而不管这些方法中的一个是否调用另一个。只有最外层 begin()/ commit()对有任何影响,所以这里的代码等同于 no begin()/ commit()调用在method_b()中。

“子交易”模式主要用于框架集成,不适用于一般用途。