如果网络接口暂时关闭,是否需要超时来防止`requests.get()`被阻塞?

问题描述 投票:0回答:1

我一直在开发应用程序,我需要在该应用程序上处理客户端上的临时断开连接(网络接口出现故障)。

我起初以为下面的方法可行,但是有时如果重新启动网络接口,s.get(url)调用将无限期挂起:

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=Retry(total=10, connect=10, read=10)))
s.get(url)

通过将timeout=10关键字参数添加到s.get(url),该代码现在能够处理这种阻塞行为:

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=Retry(total=10, connect=10, read=10)))
s.get(url, timeout=10)

为什么要超时以处理网络接口临时重置或关闭的情况?为什么max_retries=Retry(total=10, connect=10, read=10)无法处理?特别是,为什么s.get()没有通知网络接口已脱机,因此可以重试连接而不是挂起?

python sockets networking python-requests p2p
1个回答
0
投票

尝试:https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

或:

retries = Retry(connect=5, read=2, redirect=5)
http = PoolManager(retries=retries)
response = http.request('GET', 'http://stackoverflow.com')

或:

response = http.request('GET', 'http://stackoverflow.com', retries=Retry(10))
© www.soinside.com 2019 - 2024. All rights reserved.