首页 > 解决方案 > 将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

我是否需要在服务器端进行任何更改才能使其正常工作?

标签: python

解决方案


推荐阅读