重试模块未在异常上重试

问题描述 投票:2回答:2

我正在尝试使用重试模块引发异常时重试功能。但是,即使有例外,它也不会重试。例如,看看下面的代码片段。对于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)

参考:https://pypi.python.org/pypi/retrying

python exception urllib2
2个回答
1
投票

根据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)

...应该告诉它在每次失败时重试。


0
投票

您应该查看文档,但操作不正确:

[retry_on_exception需要一个函数,该函数将被调用以确定它是否应重试...如果要在任何异常情况下执行此操作,请将其关闭:

@retry(wait_random_min=1000, wait_random_max=1500, stop_max_attempt_number=10)

如果要指定特定条件:

@retry(retry_on_exception=retry_if_exception,wait_random_min=1000, wait_random_max=1500, stop_max_attempt_number=10)

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)
© www.soinside.com 2019 - 2024. All rights reserved.