python - 将keepalive http连接与`requests`一起使用的正确方法是什么?
问题描述
我正在使用带有请求库的 python3 进行休息通信。为了提高性能,我使用https://requests.kennethreitz.org/en/master/user/advanced/#session-objects会话对象来重用连接。我创建了一个会话实例,并使用它为每个用户的请求发送 rest GET 请求。
但是,当请求速率达到每秒 100 个请求时,我开始收到“连接中止”错误。痕迹是:
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 672, in urlopen
chunked=chunked,
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 421, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/usr/lib/python3.7/site-packages/urllib3/connectionpool.py", line 416, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.7/http/client.py", line 1344, in getresponse
response.begin()
File "/usr/lib/python3.7/http/client.py", line 306, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.7/http/client.py", line 267, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
它似乎达到了连接池的最大容量。我想知道如何处理这个错误。
如果我不使用会话对象,它工作正常。用于requests.post
每个请求。
代码看起来像。所以session
实例在一开始就被创建并在类方法中被重用。
session = requests.Session()
class MyClass:
def send(self):
...
session.post(...)
服务器是一个带有 uwsgi 的 python Flask 应用程序。我使用以下命令启用了保持连接:
uwsgi \
--uid uwsgi \
--master \
--plugins http,python3,stats_pusher_statsd \
--http :8880 \
--buffer-size 32768 \
--enable-threads \
--processes 1 \
--so-keepalive \
--wsgi-file uwsgi.py
我是否需要在服务器端进行任何更改才能使其正常工作?
解决方案
推荐阅读
- xcode - 防止接口名称在 OSX 包中公开
- node.js - node js中是否有任何地址验证api?
- python - 通过操作系统限制 Environment.yml 依赖项
- nfc - NFC 读取器 ACR122U 和 libnfc.driver.acr122_usb 无法写入 USB(结果太大)
- development-environment - wix 中的库存检查器 api
- action - ThingsBoard:如何在点击时打开对话框
- python - 如果条件在 python 烧瓶中的 jinja 中不起作用
- knockout.js - 剔除模板仅显示最后一个值
- python - 如何在excel中插入行
- android - DiffUtil ItemCallback areContentsTheSame() 在更新 ListAdapter 上的项目后始终返回 true