每当使用重试模块引发异常时,我都会尝试重试函数。但是,即使有异常,它也不会重试。例如,看看下面的代码片段。对于 url_list
中的第二个 URL,它应该以随机间隔重试 10 次,然后失败。谁能告诉我为什么它不重试?
import urllib2
from retrying import retry
def retry_if_exception(exception):
"""Return True if we should retry (in this case when it's any Exception), False otherwise"""
return isinstance(exception, Exception)
@retry(retry_on_exception=retry_if_exception, wait_random_min=1000, wait_random_max=1500, stop_max_attempt_number=10)
def start_http_request(url):
try:
response = urllib2.urlopen(url)
print response
except Exception as err:
retry_if_exception(err)
print (err.reason)
url_list = ['https://www.google.ca', 'http://goo123213.ca', 'http://code.activestate.com']
for url in url_list:
print url
start_http_request(url)
最佳答案
根据 retrying
的文档,retry_on_exception
应该是一个函数,如果应该重试则返回 True
。相反,您为它提供了一个类型。试试这个:
@retry(retry_on_exception=lambda e: True, wait_random_min=1000, wait_random_max=1500, stop_max_attempt_number=10)
...应该告诉它在每次失败时重试。
关于python - 重试模块不重试异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100574/