使用Gunicorn部署Flask时30秒超时断开的解决方法
Gunicorn环境下Flask传输大文件30秒断开的修复方案
问题根源
Gunicorn默认的timeout参数为30秒,当大文件传输耗时超过该阈值时,Worker进程会被强制终止,导致连接中途断开。而Flask自带的服务器无此默认超时限制,因此本地运行正常。
修复方案
1. 调整Gunicorn超时参数
直接延长Gunicorn的Worker超时时间,适配大文件传输的耗时:
- 启动命令中添加
--timeout参数:
这里将超时设置为120秒,可根据实际文件大小调整(比如几百MB的文件可能需要更长时间)。gunicorn --timeout 120 app:app - 或者通过配置文件(如
gunicorn.conf.py)设置:timeout = 120 # 单位:秒
2. 改用流式传输(推荐)
手动实现文件分块流式发送,避免Worker进程长时间被占用,从根本上减少触发超时的概率:
修改Flask代码如下:
from os import path from flask import Flask import os app = Flask(__name__) def stream_file(file_path): # 分块读取文件,每次读取1MB chunk_size = 1024 * 1024 with open(file_path, 'rb') as f: while chunk := f.read(chunk_size): yield chunk @app.route('/get_zip/<file_path>', methods=['GET']) def get_zip(file_path): full_path = path.join('archive', file_path) # 先校验文件是否存在 if not path.exists(full_path) or not path.isfile(full_path): return "指定文件不存在", 404 # 返回流式响应 return app.response_class( stream_file(full_path), headers={ 'Content-Disposition': f'attachment; filename="{file_path}"', 'Content-Type': 'application/zip' } ) if __name__ == '__main__': app.run(host="0.0.0.0", port="5000", debug=False, use_reloader=False)
3. 进阶优化:用Nginx处理静态文件
如果是超大文件(GB级),建议让Nginx直接负责静态文件传输,绕过Gunicorn:
在Nginx配置中添加静态文件映射:
location /get_zip { alias /path/to/your/archive; add_header Content-Disposition "attachment"; }
这样请求会直接由Nginx处理,既高效又不会触发Gunicorn的超时限制。
内容的提问来源于stack exchange,提问作者sixtytrees
相关产品推荐
相关产品推荐

