python - 如果网络接口暂时关闭,是否需要超时以防止 `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()
不通知网络接口离线,以便它可以重试连接而不是挂起?
解决方案
试试: 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))
推荐阅读
- javascript - “无法读取 null 的属性‘过滤器’”(与我在这里看到的其他解决方案略有不同)
- java - 需要帮助解释 Java 线程转储
- jquery - 在 NodeJS-Express 应用程序的 DOM 操作中使用 jQuery
- ios - 在领域中存储值
- php - DevTools 中的错误不再显示 XHR 响应
- python - 我无法下载 cv2,无论出于何种原因它都不起作用
- image - tensorflow仿射变换填充值
- html - 如何将跨度与h2放在同一行?
- python - 使用基本用户名和密码通过 Python 从 CloudFront 下载文件
- c++ - 显示带有二维数组的文件