python 任务由Tenacity重试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 任务由Tenacity重试相关的知识,希望对你有一定的参考价值。

#github url: https://github.com/jd/tenacity

import random
from tenacity import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print(do_something_unreliable())

#Othter example
#Let's be a little less persistent and set some boundaries, such as the number of attempts before giving up.
@retry(stop=stop_after_attempt(7))
def stop_after_7_attempts():
    print("Stopping after 7 attempts")
    raise Exception
    
#We don't have all day, so let's set a boundary for how long we should be retrying stuff.
@retry(stop=stop_after_delay(10))
def stop_after_10_s():
    print("Stopping after 10 seconds")
    raise Exception
    
#You can combine several stop conditions by using the | operator
@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
def stop_after_10_s_or_5_retries():
    print("Stopping after 10 seconds or 5 retries")
    raise Exception


以上是关于python 任务由Tenacity重试的主要内容,如果未能解决你的问题,请参考以下文章

tenacity发生异常/失败/错误时重试retry机制,Python

Python重试包 - 韧性:如何记录异常的根本原因?

快来学学优雅的库之一tenacity!!!

tenacity库 重试代码

Python之如何优雅的重试

40.少有人知的 Python“重试机制”