【问题标题】:Python tenacity: How do I retry a function without raising an exception if all retries fail?Python 坚韧:如果所有重试都失败,我如何重试函数而不引发异常?
【发布时间】:2020-09-28 21:44:49
【问题描述】:

假设我有以下功能:

@retry(stop=stop_after_attempt(3))
def foo():
  try:
    response = requests.post(...)
    response.raise_for_status()
    return response
  except Exception as e:
    raise e

这个函数会重试3次,如果3次都失败,就会抛出异常。

如何在不引发异常的情况下使用坚韧进行 3 次重试?比如:

@retry(stop=stop_after_attempt(3))
def foo(ignore_errors=False):
  try:
    response = requests.post(...)
    response.raise_for_status()
    return response
  except Exception as e:
    if ignore_errors and function has been retried three times:
      pass
    raise e

【问题讨论】:

  • 只需删除raise,并将其替换为print("Oh my god, there was an error, call the fire department!")
  • 但是如果我不在异常中引发错误,它会如何触发重试呢?

标签: python python-requests python-tenacity


【解决方案1】:

retry 装饰器有一个 retry_error_callback 参数,如果所有重试都失败,该参数可以覆盖引发 RetryError 的默认行为。这个参数应该是一个接受一个参数的函数,称为retry_state,如果你从这个函数返回一个值,如果所有重试都失败,这个值将由函数返回。

一个例子:

from tenacity import retry, stop_after_attempt

return_value_on_error = "something"

@retry(
    stop=stop_after_attempt(3),
    retry_error_callback=lambda retry_state: return_value_on_error,
)
def broken_function():
    raise RuntimeError

assert broken_function() == return_value_on_error

【讨论】:

    【解决方案2】:

    使用纯python:

    def foo(tries=0,maxTries=3):
        try:
            response = requests.post(...)
            response.raise_for_status()
            return response
        except Exception as e:
            if tries>=maxTries:
                print("Maxtries reached.")
                return
            else:
                foo(tries+1,maxTries)
    

    我不确定递归函数是否有帮助。

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2010-09-12
      相关资源
      最近更新 更多