python超時重新請求解決方案

2022-09-29 04:39:11 字數 1913 閱讀 7606

在應用中,有時候會 依賴第三方模組執行方法,比如呼叫某模組的上傳**,資料庫查詢等操作的時候,如果出現網路問題或其他問題,可能有超時重新請求的情況;

目前的解決方案有

1. 訊號量,但不支援window;

2.多執行緒,但是 如果是大量的資料重複操作嘗試,會出現執行緒管理混亂,開啟上萬個執行緒的問題;

3.結合採用 eventlet 和 retrying模組 (eventlet 原理尚需深入研究)

下面的方法實現:超過指定時間重新嘗試某個方法

# -*- 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 otherw程式設計客棧ise"""

return isinstance(exception, retrytimeoutexception)

def retry_fun(retries=3, timeout_second=2):

"""will retry $ times when process time beyond $ ;

: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_tivoqkohmeout)

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." www.cppcns.com% sleep_time)

tim程式設計客棧e.sleep(sleep_time)

print("end request...")

return true

@retry_fun(retries=3)

def retry_request():

r = do_request()

prin

if __name__ == '__main__':

retry_request()

本文標題: python超時重新請求解決方案

本文位址:

Android9 0 http網路請求解決方案

1 用retrofit請求網路報這個錯 cleartext communication to host not permitted by network 由於 android p 限制了明文流量的網路請求,非加密的流量請求都會被系統禁止掉。如果當前應用的請求是 htttp 請求,而非 https 這...

ping github請求超時解決方案

開啟 輸入 github.com 或者 github.global.ssl.fastly.net 將得到的ip位址放入到host檔案中 用管理員許可權 win10 開啟 c windows system32 drivers etc 目錄下的 host檔案 在檔案末尾加上 192.30.253.112...

pip 安裝tensorflow超時解決方案

一 各映象位址 阿里雲 中國科技大學 豆瓣 清華大學 中國科學技術大學 二 pip 使用映象安裝 tensorflow 的命令 pip install tensorflow i 三 參考鏈結 1 用anaconda安裝cpu版的tensorflow 2 anaconda切換python版本以及對應的...