我正在使用一个允许 1 个请求/秒的外部 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
对于我的问题,它似乎是一个可靠的解决方案,我不确定?此外,它是否是在重试装饰器中处理一般异常的正确方法。我正在像上面的代码一样使用它,它不会抛出任何错误但不确定。我看到的所有示例都有一些特定的异常(exception)。
更新:我得到的异常
reject |= self._retry_on_exception(attempt.value[1])
TypeError: unsupported operand type(s) for |=: 'bool' and 'exceptions.Exception'
请您参考如下方法:
您没有正确使用 retry_on_exception 参数。它需要一个可调用对象,并且该可调用对象必须返回一个 bool 值。您可以在 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"
因此,在您的情况下,您可以使用测试 isinstance(exception, Exception) 检查 Exception 实例,而不是 IOError。但是你会注意到它永远是真的,所以它有点毫无意义。 @retry 默认行为是独立于异常是什么进行重试,因此您实际上无需添加任何内容:
@retry(wait_random_min=1000, wait_random_max=2500)
def do_some_stuff(info):
#some stuff that can throw exception
但是以同样的方式处理所有类型的异常通常不是一个好主意。在您的情况下,看起来您应该只重试某些 HttpError 或您的代码在达到 API 限制时引发的任何类似错误。
