SqlAlchemy + Tornado:在回滚无效事务之前无法重新连接

时间:2014-10-04 08:17:24

标签: python mysql web-applications sqlalchemy tornado

我正在建立一个龙卷风+ sqlalchemy的webapp并且绝对随机我收到了这个错误

     File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception
    exc_info
  File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 187, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "/usr/lib/python3/dist-packages/sqlalchemy/util/compat.py", line 182, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 822, in _execute_context
    conn = self._revalidate_connection()
  File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 239, in _revalidate_connection
    "Can't reconnect until invalid "
sqlalchemy.exc.StatementError: Can't reconnect until invalid transaction is rolled back

我无法弄清楚如何解决这个问题。我已将所有db.commit放入

try:
  self.db.commit()
except Exception(e):
  self.db.rollback()

那是我的班级申请。

class Application
        [...]
        engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug)
        models.init_db(engine)
        self.db = scoped_session(sessionmaker(bind=engine))
        tornado.web.Application.__init__(self, handlers, **settings)

但没有。 为mysql + php等网络应用配置sqlalchemy和tornado的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我记得刚才有同样的问题。似乎有一些与连接池有关的奇怪的东西。禁用池似乎修复了它。 一般来说不是最好的主意,但它确实有效。

尝试将poolclass=NullPool传递给create_engine

...
from sqlalchemy.pool import NullPool
...
engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug, poolclass=NullPool)

答案 1 :(得分:1)

我的方法是在完成时回滚,将其添加到您的BaseHandler:

def on_finish(self):
    if self.get_status() == 500:
        self.db_session.rollback()