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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章