4

假设我有以下功能:

@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
4

2 回答 2

1

如果所有重试都失败,retry装饰器有一个retry_error_callback参数可以覆盖引发 a 的默认行为。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
于 2021-08-06T19:33:32.107 回答
-1

使用纯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-10-09T05:16:55.973 回答