首页 > 解决方案 > 如何让我的请求会话在超时时自动重试?

问题描述

我试图理解为什么我的请求会话在 20 秒后请求超时时不会自动重试。我的印象是我配置的重试设置会导致会话在超时时自动重试,但我得到以下异常:

# yada yada
socket.timeout: The write operation timed out  
During handling of the above exception, another exception occurred:  
# yada yada
urllib3.exceptions.ProtocolError: ('Connection aborted.', timeout('The write operation timed out',))

下面是我如何配置 Session 对象并发出请求的片段:

import requests
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter

session = requests.Session()
settings = Retry( total = 10, backoff_factor = 0.1, status_forcelist = [ 500, 502, 503, 504 ] )                     
session.mount( "https://", HTTPAdapter( max_retries = settings ) )

resp = session.post( uploadAddress, files={"file": myFile}, timeout=20 )

我似乎无法在官方文档中找到有关将 Retry 对象与 timeout 参数结合使用的有用信息,因此可能无法简单地做到这一点。

标签: python-3.xpython-requests

解决方案


推荐阅读