gpt4 book ai didi

mysql - SQLAlchemy InvalidRequestError('Transaction XXX is not on the active transaction list) 是如何发生的?

转载 作者:行者123 更新时间:2023-11-29 14:08:17 26 4
gpt4 key购买 nike

最近我遇到了 SQLAlchemy InvalidRequestError。错误日志显示:

InvalidRequestError: Transaction <sqlalchemy.orm.session.SessionTransaction object at
0x106830dd0> is not on the active transaction list

什么情况下会出现这个错误???

-----编辑----

# the following two line actually in my decorator
s = Session()
s.add(model1)

# refer to <http://techspot.zzzeek.org/2012/01/11/django-style-database-routers-in-sqlalchemy/>
s2 = Session().using_bind('master')

model2 = s2.query(Model2).with_lockmode('update').get(1)
model2.somecolumn = 'new'

s2.commit()

引发此异常

-----编辑2-----

s = Session().using_bind('master')


model = Model(user_id=123456)
s.add(model)
s.flush()
# here, raise the exception.
# I add log in get_bind() of RoutingSession. when doing 'flush', the _name is None, and it returns engines['slave'].
#If I use commit() instead of flush(), then it commits successfully

我将 using_bind 方法更改如下,效果很好。

def using_bind(self, name):
self._name = name
return self

上一个路由 session :

class RoutingSession(Session):
_name = None

def get_bind(self, mapper=None, clause=None):
logger.info(self._name)
if self._name:
return engines[self._name]
elif self._flushing:
logger.info('master')
return engines['master']
else:
logger.info('slave')
return engines['slave']

def using_bind(self, name):
s = RoutingSession()
vars(s).update(vars(self))
s._name = name
return s

最佳答案

这是一个永远不应该发生的内部断言。如果您可能不正确地以并发方式使用 session ,或者操纵其内部结构,那么至少没有完整的堆栈跟踪就无法回答这个问题。我只能显示在操作与 Session 对象相关的私有(private)方法或状态时引发的异常。

这是:

from sqlalchemy.orm import Session

s = Session()
s2 = Session()

t = s.transaction
t2 = s2.transaction

s2.transaction = t # nonsensical assignment of the SessionTransaction
# from one Session to also be referred to by another,
# corrupts the transaction chain by leaving out "t2".
# ".transaction" should never be assigned to on the outside

t2.rollback() # triggers the assertion case

基本上,上述情况永远不会发生,因为您不应该分配给“.transaction”。这是一个只读属性。

关于mysql - SQLAlchemy InvalidRequestError('Transaction XXX is not on the active transaction list) 是如何发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13968854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com