将通用异常传递给重试模块

时间:2015-05-04 15:59:40

标签: python

我正在使用允许1request / sec的外部api,以避免请求冲突,我在python中使用重试模块。我想重试一般异常并尝试使用随机时间框架。

@retry(retry_on_exception=exceptions.Exception,wrap_exception=True,wait_random_min=1000,wait_random_max=2500)
def do_some _stuff(info):
      #some stuff that can throw exception

对我的问题来说,它似乎是一个强大的解决方案吗,我不确定?此外,它是在重试装饰器中处理通用异常的正确方法。我正在使用它完全像上面的代码,它不会抛出任何错误但不确定。我见过的所有例子都有一些特殊例外。

更新:我遇到的例外情况

reject |= self._retry_on_exception(attempt.value[1])
TypeError: unsupported operand type(s) for |=: 'bool' and 'exceptions.Exception'

1 个答案:

答案 0 :(得分:1)

您没有正确使用retry_on_exception参数。它期望一个可调用的,并且可调用的必须返回一个布尔值。您可以在package doc中找到相关示例:

def retry_if_io_error(exception):
    """Return True if we should retry (in this case when it's an IOError), False otherwise"""
    return isinstance(exception, IOError)

@retry(retry_on_exception=retry_if_io_error)
def might_io_error():
    print "Retry forever with no wait if an IOError occurs, raise any other errors"

因此,在您的情况下,您可以使用测试Exception检查IOError个实例,而不是isinstance(exception, Exception)。但你可以注意到它永远都是真的,所以它毫无意义。 @retry默认行为是独立于异常重试,因此您实际上无需添加任何内容:

@retry(wait_random_min=1000, wait_random_max=2500)
def do_some_stuff(info):
      #some stuff that can throw exception

但以同样的方式处理所有类型的异常通常是一个坏主意。在您的情况下,看起来您应该只重试某些HttpError或您的代码在达到API限制时引发的类似错误。