gpt4 book ai didi

python - 是否可以在请求中刷新 session ?

转载 作者:可可西里 更新时间:2023-11-01 17:07:34 45 4
gpt4 key购买 nike

我使用 requests.Session() 创建一个 session 。由于某种原因,服务器端关闭了这个连接,所以我必须重新连接。问题是,这个 session 在很多地方都用到了,所以我想知道是否可以重建 TCP 连接但保留 session 对象以便我仍然可以使用它?

例子:

s = requests.Session()

class B:
def __init__(self, session):
self._session = session

def get(self):
self._session.get('some_url')

b1 = B(s)
b2 = B(s)
b3 = B(s)

# some get calls
...
# then connection is closed

# some get calls
...

如果我可以保留 seesion 对象,则无需替换每个 B 实例中的每个 _session

错误日志:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 376, in _make_request
httplib_response = conn.getresponse(buffering=True)
TypeError: getresponse() got an unexpected keyword argument 'buffering'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 559, in urlopen
body=body, headers=headers)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 378, in _make_request
httplib_response = conn.getresponse()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1174, in getresponse
response.begin()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 282, in begin
version, status, reason = self._read_status()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 243, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 571, in readinto
return self._sock.recv_into(b)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 924, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 786, in read
return self._sslobj.read(len, buffer)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 570, in read
v = self._sslobj.read(len, buffer)
ConnectionResetError: [Errno 54] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/adapters.py", line 376, in send
timeout=timeout
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 609, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/util/retry.py", line 247, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/packages/six.py", line 309, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 559, in urlopen
body=body, headers=headers)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/connectionpool.py", line 378, in _make_request
httplib_response = conn.getresponse()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 1174, in getresponse
response.begin()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 282, in begin
version, status, reason = self._read_status()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 243, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/socket.py", line 571, in readinto
return self._sock.recv_into(b)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 924, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 786, in read
return self._sslobj.read(len, buffer)
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 570, in read
v = self._sslobj.read(len, buffer)
requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/laike9m/ICT/zhihu-analysis/dynamic/main.py", line 108, in <module>
main()
File "/Users/laike9m/ICT/zhihu-analysis/dynamic/main.py", line 89, in main
m.detect_new_question()
File "/Users/laike9m/ICT/zhihu-analysis/dynamic/monitor.py", line 32, in detect_new_question
question = latest_question = next(it)
File "/usr/local/lib/python3.5/site-packages/zhihu/topic.py", line 269, in questions
res = self._session.get(question_url, params=params)
File "/usr/local/lib/python3.5/site-packages/requests/sessions.py", line 480, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python3.5/site-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.5/site-packages/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.5/site-packages/requests/adapters.py", line 426, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer'))

这是一个非常常见的问题:Python handling socket.error: [Errno 104] Connection reset by peer .我无法控制服务器,所以我不知道为什么或如何发生这种情况。

服务器确实支持保持事件状态,因为我可以发出数百个请求(持续一个小时或更长时间)。

最佳答案

要么使您的 B() 成为单例,要么使 session 成为类属性(从而有效地成为全局属性)。

例如,仅当您创建至少一个实例时才将其设为类属性可能如下所示:

class B:
def __init__(self):
if not hasattr(type(self), '_session'):
self._create_session()

@classmethod
def _create_session(cls):
cls._session = requests.Session()

def get(self):
self._session.get('some_url')

如果使用 session 会引发异常,因为服务器没有正确关闭 session 连接,此时只需重新创建 session :

    def __init__(self):
if not hasattr(type(self), '_session'):
self._create_session()

@classmethod
def _create_session(cls):
cls._session = requests.Session()

def get(self):
retries = 5
while retries:
try:
return self._session.get('some_url')
except requests.ConnectionException as e:
last_connection_exception = e
retries -= 1
raise last_connection_exception

以上示例最多重试 5 次。您不需要每次都重新创建 session 。如果连接已关闭,即使出现异常, session 对象也只会为下一个请求创建 TCP/IP 连接。

如果您发现 session 对象以某种方式被删除并且不再能够创建新的连接,而新的 session 仍然有效,那么这就是一个错误。请使用合适的 MCVE 将其报告给项目。

关于python - 是否可以在请求中刷新 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34747080/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com