python 重試策略

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容