[英]What's wrong with this python decorator?
我有以下裝飾器,應處理“無網絡”異常:
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
但是它根本不起作用,當我的LAN適配器處於斷開狀態時,甚至沒有“連接不良或斷開,請重試...”輸出,它什么也沒顯示。 這是func的定義和調用:
@reTryer(5,5)
def func(arg):
#some code
func(arg)
我想念什么嗎?
要回答您的問題:
由於實現似乎是正確的,所以我可以想象一些可能導致問題的原因。
我主要想到的是裝飾函數永遠不會返回,拋出與您關注的異常不同的異常,甚至不會返回正常。
你可以用
@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
我懂了
>>> 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.