python 超时重试方法
生活随笔
收集整理的這篇文章主要介紹了
python 超时重试方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在應(yīng)用中,有時(shí)候會(huì) 依賴第三方模塊執(zhí)行方法,比如調(diào)用某模塊的上傳下載,數(shù)據(jù)庫查詢等操作的時(shí)候,如果出現(xiàn)網(wǎng)絡(luò)問題或其他問題,可能有超時(shí)重新請(qǐng)求的情況;
目前的解決方案有
信號(hào)量,但不支持window;
多線程,但是 如果是大量的數(shù)據(jù)重復(fù)操作嘗試,會(huì)出現(xiàn)線程管理混亂,開啟上萬個(gè)線程的問題;
結(jié)合采用 eventlet 和 retrying模塊 (eventlet 原理尚需深入研究)
下面的方法實(shí)現(xiàn):超過指定時(shí)間重新嘗試某個(gè)方法
''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' # -*- coding: utf-8 -*- import random import timeimport eventlet from retrying import retryeventlet.monkey_patch()class RetryTimeOutException(Exception):def __init__(self, *args, **kwargs):passdef retry_if_timeout(exception):"""Return True if we should retry (in this case when it's an IOError), False otherwise"""return isinstance(exception, RetryTimeOutException)def retry_fun(retries=3, timeout_second=2):"""will retry ${retries} times when process time beyond ${timeout_second} ;:param retries: The retry times:param timeout_second: The max process time"""def retry_decor(func):@retry(stop_max_attempt_number=retries, retry_on_exception=retry_if_timeout)def decor(*args, **kwargs):print("In retry method..")pass_flag = Falsewith eventlet.Timeout(timeout_second, False):r = func(*args, **kwargs)pass_flag = Trueprint("Success after method.")if not pass_flag:raise RetryTimeOutException("Time out..")print("Exit from retry.")return rreturn decorreturn retry_decordef do_request():print("begin request...")sleep_time = random.randint(1, 4)print("request sleep time: %s." % sleep_time)time.sleep(sleep_time)print("end request...")return True@retry_fun(retries=3) def retry_request():r = do_request()print(r)if __name__ == '__main__':retry_request() 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python 超时重试方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python文件读写、StringIO和
- 下一篇: python中operator.item