我已經編寫了代碼來處理整個我的應用程序中的嵌套事務。但是當它回滾一次之後,所有事務都會回滾,直到我重新啓動應用程序。如何在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)
您使用的是哪個引擎? –
將'except:'替換爲'SomeSpecificExceptionClass:'除外。 'except:'捕獲所有*錯誤,而您可能只想捕獲數據庫引發的某些特定錯誤。 – Bakuriu
我正在使用mysql InoDB存儲引擎 – pravin4659