溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

什么是Python重試機制

發(fā)布時間:2021-10-29 17:54:18 來源:億速云 閱讀:133 作者:iii 欄目:編程語言

這篇文章主要講解了“什么是Python重試機制”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“什么是Python重試機制”吧!

為了避免由于一些網(wǎng)絡或等其他不可控因素,而引起的功能性問題。比如在發(fā)送請求時,會因為網(wǎng)絡不穩(wěn)定,往往會有請求超時的問題。

這種情況下,我們通常會在代碼中加入重試的代碼。重試的代碼本身不難實現(xiàn),但如何寫得優(yōu)雅、易用,是我們要考慮的問題。

這里要給大家介紹的是一個第三方庫 - Tenacity (標題中的重試機制并并不準確,它不是 Python  的內(nèi)置模塊,因此并不能稱之為機制),它實現(xiàn)了幾乎我們可以使用到的所有重試場景,比如:

  1. 在什么情況下才進行重試?

  2. 重試幾次呢?

  3. 重試多久后結束?

  4. 每次重試的間隔多長呢?

  5. 重試失敗后的回調(diào)?

在使用它之前 ,先要安裝它

$ pip install tenacity

1. 最基本的重試

無條件重試,重試之間無間隔

from tenacity import retry  @retry def test_retry():     print("等待重試,重試無間隔執(zhí)行...")     raise Exception  test_retry()

無條件重試,但是在重試之前要等待 2 秒

from tenacity import retry, wait_fixed  @retry(wait=wait_fixed(2)) def test_retry():     print("等待重試...")     raise Exception  test_retry()

2. 設置停止基本條件

只重試7 次

from tenacity import retry, stop_after_attempt  @retry(stop=stop_after_attempt(7)) def test_retry():     print("等待重試...")     raise Exception  test_retry()

重試 10 秒后不再重試

from tenacity import retry, stop_after_delay  @retry(stop=stop_after_delay(10)) def test_retry():     print("等待重試...")     raise Exception  test_retry()

或者上面兩個條件滿足一個就結束重試

from tenacity import retry, stop_after_delay, stop_after_attempt  @retry(stop=(stop_after_delay(10) | stop_after_attempt(7))) def test_retry():     print("等待重試...")     raise Exception  test_retry()

3. 設置何時進行重試

在出現(xiàn)特定錯誤/異常(比如請求超時)的情況下,再進行重試

from requests import exceptions from tenacity import retry, retry_if_exception_type  @retry(retry=retry_if_exception_type(exceptions.Timeout)) def test_retry():     print("等待重試...")     raise exceptions.Timeout  test_retry()

在滿足自定義條件時,再進行重試。

如下示例,當 test_retry 函數(shù)返回值為 False 時,再進行重試

from tenacity import retry, stop_after_attempt, retry_if_result  def is_false(value):     return value is False  @retry(stop=stop_after_attempt(3),        retry=retry_if_result(is_false)) def test_retry():     return False  test_retry()

4. 重試后錯誤重新拋出

當出現(xiàn)異常后,tenacity 會進行重試,若重試后還是失敗,默認情況下,往上拋出的異常會變成  RetryError,而不是最根本的原因。

因此可以加一個參數(shù)(reraise=True),使得當重試失敗后,往外拋出的異常還是原來的那個。

from tenacity import retry, stop_after_attempt  @retry(stop=stop_after_attempt(7), reraise=True) def test_retry():     print("等待重試...")     raise Exception  test_retry()

5. 設置回調(diào)函數(shù)

當最后一次重試失敗后,可以執(zhí)行一個回調(diào)函數(shù)

from tenacity import *  def return_last_value(retry_state):     print("執(zhí)行回調(diào)函數(shù)")     return retry_state.outcome.result()  # 表示返回原函數(shù)的返回值  def is_false(value):     return value is False  @retry(stop=stop_after_attempt(3),        retry_error_callback=return_last_value,        retry=retry_if_result(is_false)) def test_retry():     print("等待重試中...")     return False  print(test_retry())

輸出如下

等待重試中... 等待重試中... 等待重試中... 執(zhí)行回調(diào)函數(shù) False

感謝各位的閱讀,以上就是“什么是Python重試機制”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對什么是Python重試機制這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI