gpt4 book ai didi

python - SQLAlchemy:在回滚无效事务之前无法重新连接

转载 作者:行者123 更新时间:2023-12-03 14:16:24 25 4
gpt4 key购买 nike

我有一个奇怪的问题。
我有一个简单的 py3 应用程序,它使用 sqlalchemy。

但几个小时后,出现了错误:

(sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back



我的初始化部分:
self.db_engine = create_engine(self.db_config, pool_pre_ping=True) # echo=True if needed to see background SQL
Session = sessionmaker(bind=self.db_engine)
self.db_session = Session()

查询(这是唯一发生的查询):
while True:
device_id = self.db_session.query(Device).filter(Device.owned_by == msg['user_id']).first()
sleep(20)

整个脚本处于无限循环中,单线程(SQS 读出)。有人解决这个问题吗?

最佳答案

解决方案:
不要让您的连接长时间打开。
SQLAlchemy 文档也共享相同的解决方案:session basics

@contextmanager
def session_scope(self):
self.db_engine = create_engine(self.db_config, pool_pre_ping=True) # echo=True if needed to see background SQL
Session = sessionmaker(bind=self.db_engine)
session = Session()
try:
# this is where the "work" happens!
yield session
# always commit changes!
session.commit()
except:
# if any kind of exception occurs, rollback transaction
session.rollback()
raise
finally:
session.close()

关于python - SQLAlchemy:在回滚无效事务之前无法重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58378708/

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