Tenacity是一個 Apache 2.0受權的通用重試庫,用 Python 編寫,用於簡化向幾乎全部內容添加劇試行爲的任務。它起源於一個從新嘗試的分支,惋惜這個分支已經不復存在了。
使用Tenacity能夠用來進行測試用例的重跑,爬蟲腳本的重跑,以及搶票的失敗重搶等等。。。可使用的場景也是比較多。python
首先安裝Tenacitygit
pip install Tenacity
第一個重試案例,由於一直是拋出異常錯誤,因此無限進行重試執行github
from tenacity import retry @retry() def test_retry(): print('失敗重試中') raise Exception test_retry()
咱們來優化成功一次後程序則終止,不然繼續重試。shell
from tenacity import retry import random @retry() def test_retry(): if random.randint(0,10) > 1: print('失敗重試中') raise Exception else: print('成功') test_retry()
畢竟一直重試須要消耗不少資源,因此咱們能夠設置一些重試的次數,好比在失敗多少次後中止重試,無論有沒有成功。dom
from tenacity import retry,stop_after_attempt import random @retry(stop=stop_after_attempt(7)) def test_retry(): # if random.randint(0,10) > 1: print('失敗重試中') raise Exception # else: # print('成功') test_retry()
也能夠設置執行的時間測試
from tenacity import retry,stop_after_attempt,stop_after_delay import random from time import sleep @retry(stop=stop_after_delay(3)) def test_retry(): # if random.randint(0,10) > 1: sleep(1) print('失敗重試中') raise Exception # else: # print('成功') test_retry()
甚至可使用多個組合條件進行中止,哪一個條件先觸發則執行哪一個優化
from tenacity import retry,stop_after_attempt,stop_after_delay import random from time import sleep @retry(stop=stop_after_delay(3) | stop_after_attempt(2)) def test_retry(): # if random.randint(0,10) > 1: sleep(1) print('失敗重試中') raise Exception # else: # print('成功') test_retry()
重試之間的間隔時間過短,因此讓咱們在重試之間等待2秒鐘3d
from tenacity import retry,stop_after_attempt,stop_after_delay,wait_fixed import random import time @retry(wait=wait_fixed(2)) def test_retry(): # if random.randint(0,10) > 1: print('失敗重試中') print(time.ctime()) raise Exception # else: # print('成功') test_retry()
咱們還能夠設置一些等待時間範圍日誌
from tenacity import retry,stop_after_attempt,stop_after_delay,wait_fixed,wait_random import random import time @retry(wait=wait_random(min=1,max=2)) def test_retry(): # if random.randint(0,10) > 1: print('失敗重試中') print(time.ctime()) raise Exception # else: # print('成功') test_retry()
在執行以前打印日誌code
from tenacity import retry,stop_after_attempt,before_log import logging import sys logging.basicConfig(stream=sys.stderr,level=logging.DEBUG) logger = logging.getLogger(__name__) @retry(stop=stop_after_attempt(3),before=before_log(logger,logging.DEBUG)) def test_retry(): print('失敗重試中') raise Exception('Fail') test_retry()
那麼相同的,能夠在執行失敗後打印日誌
from tenacity import retry,stop_after_attempt,after_log import logging import sys logging.basicConfig(stream=sys.stderr,level=logging.DEBUG) logger = logging.getLogger(__name__) @retry(stop=stop_after_attempt(3),after=after_log(logger,logging.DEBUG)) def test_retry(): print('失敗重試中') raise Exception('Fail') test_retry()
基本經常使用的功能就這些了,若是有須要深刻了解的能夠訪問github地址:https://github.com/jd/tenacity