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

mki*_*iss 6 python sqlalchemy python-3.x

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

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

(sqlalchemy.exc.InvalidRequestError) 在无效事务回滚之前无法重新连接

我的初始化部分:

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()
Run Code Online (Sandbox Code Playgroud)

查询(这是唯一发生的查询):

while True:
    device_id = self.db_session.query(Device).filter(Device.owned_by == msg['user_id']).first()
    sleep(20)
Run Code Online (Sandbox Code Playgroud)

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

mki*_*iss 8

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

@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()
Run Code Online (Sandbox Code Playgroud)