我一直在开发应用程序,我需要在该应用程序上处理客户端上的临时断开连接(网络接口出现故障)。
我起初以为下面的方法可行,但是有时如果重新启动网络接口,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()
没有通知网络接口已脱机,因此可以重试连接而不是挂起?
尝试: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))