簡體   English   中英

Python 重試使用沒有裝飾器的堅韌

[英]Python retry using tenacity without decorator

我正在嘗試使用堅韌(沒有裝飾器)進行重試。 我的代碼看起來像這里解釋的那樣。

import logging
from tenacity import retry
import tenacity


def print_msg():
    try:
        logging.info('Hello')
        logging.info("World")
        raise Exception('Test error')
    except Exception as e:
        logging.error('caught error')
        raise e


if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
        datefmt='%d-%m-%Y:%H:%M:%S',
        level=logging.INFO)
    logging.info('Starting')
    try:
        r = tenacity.Retrying(
            tenacity.stop_after_attempt(2),
            tenacity.wait_incrementing(start=10, increment=100, max=1000),
            reraise=True
        )
        try:
            r.call(print_msg)
        except Exception:
            logging.error('Test error 2')
    except Exception:
        logging.error('Received Exception')

在執行上面的代碼。 輸出如下所示,無需重試

/Users/dmanna/PycharmProjects/demo/venv/bin/python /Users/dmanna/PycharmProjects/demo/retrier.py
25-11-2018:00:29:47,140 INFO     [retrier.py:21] Starting
25-11-2018:00:29:47,140 INFO     [retrier.py:8] Hello
25-11-2018:00:29:47,140 INFO     [retrier.py:9] World
25-11-2018:00:29:47,140 ERROR    [retrier.py:12] caught error
25-11-2018:00:29:47,141 ERROR    [retrier.py:31] Test error 2

Process finished with exit code 0

有人可以讓我知道出了什么問題,因為我在上面的代碼中沒有看到任何重試嗎?

這已在此處得到解答。 交叉發布答案

嗯,我認為您在這里沒有正確使用 API:

 r = tenacity.Retrying( tenacity.stop_after_attempt(2), tenacity.wait_incrementing(start=10, increment=100, max=1000), reraise=True )

這轉化為:

 r = tenacity.Retrying( sleep=tenacity.stop_after_attempt(2), stop=tenacity.wait_incrementing(start=10, increment=100, max=1000), reraise=True )

這不會做你想做的。

你要:

 r = tenacity.Retrying( stop=tenacity.stop_after_attempt(2), wait=tenacity.wait_incrementing(start=10, increment=100, max=1000), reraise=True )

請注意 Python 3.4+ 用戶(支持注釋),要在 Tenacity 中顯式強制重試,一般用例是使用簡單的@retry對其進行注釋,然后引發特殊的 Exception TryAgain

@retry
def do_something():
    result = something_else()
    if result == 23:
       raise TryAgain

也可以實現類似於此頁面上Python 2.7 答案的這種方法:

import tenacity

def do_something():
    result = something_else()
    if result == 23:
       raise TryAgain

r = tenacity.Retrying(
        stop=tenacity.stop_after_attempt(2),
        wait=tenacity.wait_incrementing(start=10, increment=100, max=1000)
    )
r.wraps(do_something)

有關更多詳細信息,請參閱有關是否重試定義注釋API 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM