python 有一個(gè)非常有意思包retrying,可以用來自動(dòng)化的進(jìn)行重試操作,支持的條件也比較多,基本上能滿足我的日常需求。
在沒有用retrying之前,我的代碼結(jié)構(gòu)是這樣的:
try_times = 2
response = None
while True:
try:
response = request.post(URL)
except Exception as e:
if try_times > 0:
time.sleep(3)
try_times -= 1
else:
logger.info(response.json())
if response.json()['errno'] == 1000:
raise TimeoutError
raise Exception("failed")
代碼可以說是非常的不優(yōu)雅。retrying支持使用裝飾器來對(duì)函數(shù)單元進(jìn)行處理。改造后為
from retrying import retry
def retry_TimeoutError(exception):
return isinstance(exception, TimeoutError)
@retry(stop_max_attempt_number=3,
wait_fixed=3000,
retry_on_exception=retry_TimeoutError)
def retry_request_translate(self, content, input_len):
try:
response = requests.post(url, json=payload)
return result
except Exception as e:
if response is not None:
if response.json()['errno'] == 1000:
raise TimeoutError
raise Exception("failed")
retry的參數(shù)支持:
-
stop_max_attempt_number:最大重試次數(shù); -
wait_fixed:重試之間的間隔時(shí)間,單位為毫秒; -
retry_on_exception:捕獲特定異常才重試,例如我這里自己申明了超時(shí)的判斷; -
其它:
image.png
