python3:retrying模块

retrying是一个python的重试包,可以用来自动重试一些可能运行失败的程序段,retrying提供一个装饰器函数retry,被装饰的函数就在运行失败的情况下将重新执行,默认只要一直报错就会不断重试

Web sit:

https://github.com/rholder/retrying

https://pypi.org/project/retrying/

安装:

pip install retrying

Examples

默认行为是永远重试而不等待.

@retry
def never_give_up_never_surrender():
    print("永远重试忽略异常,不要在重试之间等待")

Let’s be a little less persistent and set some boundaries, such as the number of attempts before giving up.

让我们不那么执着,并设置一些界限,例如放弃之前的尝试次

@retry(stop_max_attempt_number=7)
def stop_after_7_attempts():
    print("7次尝试后停止")

We don’t have all day, so let’s set a boundary for how long we should be retrying stuff.

让我们设置一个边界,我们应该多久重试一下

@retry(stop_max_delay=10000)
def stop_after_10_s():
    print("10秒后停止")

Most things don’t like to be polled as fast as possible, so let’s just wait 2 seconds between retries.

大多数事情都不希望尽可能快地进行轮询,所以让我们在重试之间等待2秒钟

@retry(wait_fixed=2000)
def wait_2_s():
    print("重试之间等待2秒")

Some things perform best with a bit of randomness injected.

有些东西注入了一点随机性将会表现的更好

@retry(wait_random_min=1000, wait_random_max=2000)
def wait_random_1_to_2_s():
    print("重试之间随机等待1到2秒")

Then again, it’s hard to beat exponential backoff when retrying distributed services and other remote endpoints.

@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)
def wait_exponential_1000():
    print("每次重试之间等待2 ^ x * 1000毫秒,最多10秒,然后10秒")

We have a few options for dealing with retries that raise specific or general exceptions, as in the cases here.

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"

@retry(retry_on_exception=retry_if_io_error, wrap_exception=True)
def only_raise_retry_error_when_not_io_error():
    print "Retry forever with no wait if an IOError occurs, raise any other errors wrapped in RetryError"

We can also use the result of the function to alter the behavior of retrying.

def retry_if_result_none(result):
    """Return True if we should retry (in this case when result is None), False otherwise"""
    return result is None

@retry(retry_on_result=retry_if_result_none)
def might_return_none():
    print "Retry forever ignoring Exceptions with no wait if return value is None"

参考实例:

https://blog.csdn.net/lxy210781/article/details/94778320

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值