我想将默认超时轻松添加到一堆代码中(假设超时解决了您的问题)
这是我从提交到请求存储库的票证中挑选的解决方案。
信用:https://github.com/kennethreitz/requests/issues/2011#issuecomment-477784399
解决方案是这里的最后两行,但我展示了更多代码以提供更好的上下文。我喜欢使用会话重试行为。
import requests
import functools
from requests.adapters import HTTPAdapter,Retry
def requests_retry_session(
retries=10,
backoff_factor=2,
status_forcelist=(500, 502, 503, 504),
session=None,
) -> requests.Session:
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
# set default timeout
for method in ('get', 'options', 'head', 'post', 'put', 'patch', 'delete'):
setattr(session, method, functools.partial(getattr(session, method), timeout=30))
return session
那么您可以执行以下操作:
requests_session = requests_retry_session()
r = requests_session.get(url=url,...