1

我正在尝试使用坚韧(没有装饰器)重试。我的代码看起来像这里解释的那样。

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

有人可以告诉我出了什么问题,因为我在上面的代码中没有看到任何重试吗?

4

2 回答 2

1

这已经回答here。交叉发布答案

嗯,我认为您在这里没有正确使用 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
        )
于 2018-11-26T12:10:13.453 回答
0

对于 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 文档。

于 2020-05-03T16:32:04.477 回答