【问题标题】:How to use nested transaction with scoped session in SQLAlchemy?如何在 SQLAlchemy 中使用嵌套事务和范围会话?
【发布时间】:2012-11-11 10:18:20
【问题描述】:

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

# 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)

【问题讨论】:

  • 您使用的是哪个引擎?
  • except: 替换为except SomeSpecificExceptionClass:except: 捕获所有错误,而您可能只想捕获数据库引发的某些特定错误。
  • 我用的是mysql InoDB存储引擎

标签: python transactions python-2.7 sqlalchemy


【解决方案1】:

除非正在使用 SAVEPOINT(此处不是这种情况),否则 session.rollback() 会回滚整个事务,而不考虑嵌套。使用“子事务”嵌套的目的是,多个代码块可以各自指定它们“开始()”和“提交()”一个事务,而与这些方法中的一个是否调用另一个无关。只有 outermost begin()/commit() 对有任何影响,所以这里的代码相当于有 no begin()/commit() 调用在 method_b() 中。

“子事务”模式的存在主要是为了框架集成,而不是一般用途。

【讨论】:

猜你喜欢
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多