python超時重新請求解決方案
在應(yīng)用中,有時候會 依賴第三方模塊執(zhí)行方法,比如調(diào)用某模塊的上傳下載,數(shù)據(jù)庫查詢等操作的時候,如果出現(xiàn)網(wǎng)絡(luò)問題或其他問題,可能有超時重新請求的情況;
目前的解決方案有
1. 信號量,但不支持window;
2.多線程,但是 如果是大量的數(shù)據(jù)重復操作嘗試,會出現(xiàn)線程管理混亂,開啟上萬個線程的問題;
3.結(jié)合采用 eventlet 和 retrying模塊 (eventlet 原理尚需深入研究)
下面的方法實現(xiàn):超過指定時間重新嘗試某個方法
# -*- 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()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python datetime 和時間戳互相轉(zhuǎn)換問題
time和datetime都是Python中的內(nèi)置模塊(不需要安裝,直接可以使用),都可以對時間進行獲取,對時間格式進行轉(zhuǎn)換,如時間戳和時間字符串的相互轉(zhuǎn)換,本文先給大家介紹python datetime 和時間戳互轉(zhuǎn)問題,感興趣的朋友一起看看吧2022-11-11
Python Dict 到 Dataclass實現(xiàn)高效數(shù)據(jù)訪問與管理的兩種方式(推薦)
本文介紹了Python中的字典和DataClass兩種數(shù)據(jù)結(jié)構(gòu),并探討了如何將字典轉(zhuǎn)換為DataClass,字典適用于鍵值對存儲,感興趣的朋友一起看看吧2024-12-12
Python中使用__new__實現(xiàn)單例模式并解析
單例模式是一個經(jīng)典設(shè)計模式,簡要的說,一個類的單例模式就是它只能被實例化一次,實例變量在第一次實例化時就已經(jīng)固定。 這篇文章主要介紹了Python中使用__new__實現(xiàn)單例模式并解析 ,需要的朋友可以參考下2019-06-06
python 數(shù)字轉(zhuǎn)換為日期的三種實現(xiàn)方法
在Python中,我們經(jīng)常需要處理日期和時間,本文主要介紹了python 數(shù)字轉(zhuǎn)換為日期的三種實現(xiàn)方法,包含datetime模塊,strftime方法及pandas庫,具有一定的參考價值,感興趣的可以了解一下2024-02-02

