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

关闭uWSGI master模式时,如何实现Flask应用自动重载?

解决uWSGI master=false时无法自动重载Flask服务的问题

导入pandas、google.cloud.bigquery库后,开启uWSGI的master=true会触发监听队列满的错误:

uWSGI listen queue of socket "localhost:5000" (fd: 3) full !!! (2871782829/10922)
疑似与PIL相关,因此必须设置master=false,但该配置下py-autoreload=1无法实现文件变更自动重载。以下是可行的解决办法:

方案1:用外部文件监控工具触发uWSGI重启

放弃uWSGI自带的自动重载,借助外部工具监控代码目录变化,触发uWSGI进程重启:

  • 安装inotify-tools(Linux环境):
    sudo apt-get install inotify-tools  # Debian/Ubuntu系
    # 或
    sudo yum install inotify-tools      # CentOS/RHEL系
    
  • 创建监控脚本watch_and_restart.sh:
    #!/bin/bash
    UWSGI_PID=$(pgrep uwsgi)
    inotifywait -m -r -e modify,create,delete /opt/merlin/ | while read path action file; do
        echo "Detected change in $path$file, restarting uWSGI..."
        kill -HUP $UWSGI_PID
    done
    
  • 给脚本添加执行权限:chmod +x watch_and_restart.sh
  • 后台运行脚本:nohup ./watch_and_restart.sh > /var/log/merlin/reload.log 2>&1 &
    该脚本会监控/opt/merlin/目录下所有文件的修改、创建、删除操作,一旦触发就向uWSGI进程发送HUP信号实现重启。

方案2:调整uWSGI配置,尝试修复master=true的报错

针对疑似PIL导致的监听队列问题,通过配置参数规避冲突,重新开启master=true以恢复自带自动重载:

  • 修改uWSGI配置文件:
    [uwsgi]
    master = true
    enable-threads = true
    wsgi-file = /opt/merlin/main.py
    callable = app
    protocol = http
    http-socket = localhost:5000
    daemonize = /var/log/merlin/merlin-app.log
    env = FLASK_ENV=development
    py-autoreload = 1
    # 添加参数解决监听队列与库加载冲突
    listen = 20480  # 增大监听队列长度,可根据服务器资源调整
    lazy-apps = true  # 让每个worker单独加载应用,避免master进程初始化库时的冲突
    
  • 重启uWSGI后观察是否仍出现监听队列满的错误。lazy-apps=true能避免master进程加载PIL等库后复制给worker导致的资源占用问题。

方案3:开发环境使用Flask自带调试模式

如果仅在开发阶段使用,可直接用Flask自带的调试服务器实现自动重载:

  • 在main.py中添加启动代码:
    if __name__ == '__main__':
        app.run(host='localhost', port=5000, debug=True)
    
  • 直接运行脚本启动服务:python /opt/merlin/main.py
    注意:该模式仅适用于开发环境,禁止在生产环境使用。

内容的提问来源于stack exchange,提问作者Mahesh Bansod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:32:42