FastAPI+Gunicorn部署后/test路由调用外部接口无响应问题
macOS下Gunicorn部署FastAPI调用外部请求返回ERR_EMPTY_RESPONSE的解决方法
问题背景
部署命令:
gunicorn main:app -b 0.0.0.0:9700 -w 4 -k uvicorn.workers.UvicornWorker --timeout 600
异常表现:/test路由调用requests.get("https://google.com")时返回ERR_EMPTY_RESPONSE,移除该外部请求后路由正常响应;单独用Uvicorn启动或Ubuntu系统下Gunicorn部署均无此问题。
解决方案
1. 捕获请求异常,定位具体错误
先给requests请求添加超时限制和异常捕获,明确是连接超时、DNS解析失败还是其他网络问题:
@app.get('/test') def test(): try: r = requests.get("https://google.com", timeout=10) r.raise_for_status() # 抛出HTTP状态码异常 return {'code': 0, 'msg': '123', 'status_code': r.status_code} except Exception as e: return {'code': 1, 'msg': str(e)}
重新部署后访问/test,根据返回的错误信息针对性处理。
2. 检查macOS代理与环境变量
macOS下多进程应用可能无法继承系统代理设置,导致外部请求失败:
- 临时关闭系统代理/VPN,重新启动Gunicorn测试;
- 如果必须使用代理,在启动命令前显式指定代理环境变量:
HTTP_PROXY=http://your-proxy-addr:port HTTPS_PROXY=http://your-proxy-addr:port gunicorn main:app -b 0.0.0.0:9700 -w 4 -k uvicorn.workers.UvicornWorker --timeout 600
3. 调整Gunicorn Worker配置
多进程模式下macOS可能存在网络资源竞争问题,先尝试单Worker测试:
gunicorn main:app -b 0.0.0.0:9700 -w 1 -k uvicorn.workers.UvicornWorker --timeout 600
如果单Worker正常,说明多进程网络请求存在冲突,可尝试降低Worker数量,或改用异步请求适配框架特性。
4. 切换为异步HTTP客户端
FastAPI是异步框架,同步的requests在多进程环境下可能引发阻塞问题,改用aiohttp异步请求适配框架设计:
- 安装依赖:
pip install aiohttp - 修改代码:
import aiohttp from fastapi import FastAPI app = FastAPI() @app.get('/') def index(): return 'hello' @app.get('/test') async def test(): async with aiohttp.ClientSession() as session: async with session.get("https://google.com", timeout=10) as r: return {'code': 0, 'msg': '123', 'status_code': r.status}
5. 检查macOS防火墙设置
进入「系统偏好设置」→「安全性与隐私」→「防火墙」,确认Python或Gunicorn进程被允许出站网络访问,若被阻止则添加允许规则。
内容的提问来源于stack exchange,提问作者黎谷歌
相关产品推荐
相关产品推荐

