我有以下的裝飾應處理「無網絡」例外:這個python裝飾器有什麼問題?
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)
我是否錯過了什麼?
你嘗試在'inner'功能來定義的元組'request_exceptions'? – Frodon
@Frodon會發生什麼變化? – glglgl
@Frodon無關緊要,內部函數可以訪問外部函數範圍內的任何變量。 –