You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask+SQLAlchemy在uWSGI生产环境启动初期MySQL连接异常问题求助

Flask+SQLAlchemy在uWSGI生产环境启动初期MySQL连接异常问题求助

大家好,我最近碰到个闹心的小问题,想请各位帮忙支支招:

我的Flask+SQLAlchemy应用在生产环境(用uWSGI部署)启动或者重启后的头一分钟里,会接连抛出一堆SQLAlchemy的数据库连接异常,但过了这阵子之后就一切恢复正常了。虽然不算严重故障,但每次重启都要刷这些错误日志,看着特别烦。

我遇到的异常主要有这些:

  • sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2006, 'MySQL server has gone away') (这个出现得最频繁)
  • sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically.
  • sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column 'users.id'"
  • sqlalchemy.exc.NoSuchColumnError: "Could not locate column in row for column 'payments.id'"
  • sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2013, 'Lost connection to MySQL server during query')

奇怪的是,这个问题只在生产环境的uWSGI上出现,本地开发环境完全没这回事。

我自己试着在应用启动时做了数据库连接预热,写了这么一段代码:

with app.app_context():
    for _ in range(5):
        try:
            db.session.execute(statement)
            logger.info("DB connection is successfully established")
            return
        except Exception as e:
            logger.warning(e)
            time.sleep(1)
    raise Exception("Couldn't establish a DB connection")

这段预热代码每次都能顺利执行,日志也显示连接成功建立了,但启动初期的异常问题还是没解决。

补充一下,我的数据库连接URI是这样的:

mysql+mysqldb://user:password@localhost/mydb?unix_socket=/var/run/mysqld/mysqld.sock

有没有大佬知道这是啥原因,或者有什么可行的解决办法吗?

备注:内容来源于stack exchange,提问作者Ralfeus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 11:29:36