首页 > 解决方案 > 如果网络接口暂时关闭,是否需要超时以防止 `requests.get()` 阻塞?

问题描述

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

我最初认为下面的方法会起作用,但有时如果重新启动网络接口,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()不通知网络接口离线,以便它可以重试连接而不是挂起?

标签: pythonsocketsnetworkingpython-requestsp2p

解决方案


试试: 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))

推荐阅读