简体   繁体   English

这个python装饰器有什么问题?

[英]What's wrong with this python decorator?

I have the following decorator that should handle "no network" exceptions: 我有以下装饰器,应处理“无网络”异常:

class NetworkError(RuntimeError):
    pass

def reTryer(max_retries=5, timeout=5):
    def wraper(func):
        request_exceptions = (
            requests.exceptions.Timeout,
            requests.exceptions.ConnectionError,
            requests.exceptions.HTTPError
        )
        def inner(*args, **kwargs):
            for i in range(max_retries):
                try:
                    result = func(*args, **kwargs)
                except request_exceptions:
                    time.sleep(timeout)
                    print("Bad or broken connection, trying again...")
                    continue
                else:
                    return result
            else:
                raise NetworkError
        return inner
    return wraper

But it doesn't work at all, there is even no "Bad or broken connection, trying again..." output when my LAN adapter is in disconnected state, it just shows nothing. 但是它根本不起作用,当我的LAN适配器处于断开状态时,甚至没有“连接不良或断开,请重试...”输出,它什么也没显示。 This is func definition and call: 这是func的定义和调用:

@reTryer(5,5)
def func(arg):
    #some code

func(arg)

Am I missing something? 我想念什么吗?

To answer your question: 要回答您的问题:

As the implementation seems correct, I can imagine some things which could be the cause of the problem. 由于实现似乎是正确的,所以我可以想象一些可能导致问题的原因。

Mainly I think about the decorated function never returning, throwing a different exception than you had in focus, or even returning normal. 我主要想到的是装饰函数永远不会返回,抛出与您关注的异常不同的异常,甚至不会返回正常。

You could test this with 你可以用

@reTryer(2, 1.0)
def always_ok():
    print "ok"

@reTryer(2, 1.0)
def always_good_error():
    print "good error"
    raise requests.exceptions.Timeout

@reTryer(2, 1.0)
def always_bad_error():
    print "bad error"
    raise RuntimeError

I get 我懂了

>>> always_ok()
ok
>>> import time
>>> always_good_error()
good error
Bad or broken connection, trying again...
good error
Bad or broken connection, trying again...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 17, in inner
__main__.NetworkError
>>> always_bad_error()
bad error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in inner
  File "<stdin>", line 4, in always_bad_error
RuntimeError
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM