您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何解決python超時(shí)重新請(qǐng)求問(wèn)題”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何解決python超時(shí)重新請(qǐng)求問(wèn)題”這篇文章吧。
在應(yīng)用中,有時(shí)候會(huì) 依賴(lài)第三方模塊執(zhí)行方法,比如調(diào)用某模塊的上傳下載,數(shù)據(jù)庫(kù)查詢(xún)等操作的時(shí)候,如果出現(xiàn)網(wǎng)絡(luò)問(wèn)題或其他問(wèn)題,可能有超時(shí)重新請(qǐng)求的情況;
目前的解決方案有
1. 信號(hào)量,但不支持window;
2.多線程,但是 如果是大量的數(shù)據(jù)重復(fù)操作嘗試,會(huì)出現(xiàn)線程管理混亂,開(kāi)啟上萬(wàn)個(gè)線程的問(wèn)題;
3.結(jié)合采用 eventlet 和 retrying模塊 (eventlet 原理尚需深入研究)
下面的方法實(shí)現(xiàn):超過(guò)指定時(shí)間重新嘗試某個(gè)方法
# -*- coding: utf-8 -*- import random import time import eventlet from retrying import retry eventlet.monkey_patch() class RetryTimeOutException(Exception): def __init__(self, *args, **kwargs): pass def 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 = False with eventlet.Timeout(timeout_second, False): r = func(*args, **kwargs) pass_flag = True print("Success after method.") if not pass_flag: raise RetryTimeOutException("Time out..") print("Exit from retry.") return r return decor return retry_decor def 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()
以上是“如何解決python超時(shí)重新請(qǐng)求問(wèn)題”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。