python超时重新请求解决方案

yipeiwu_com5年前Python基础

在应用中,有时候会 依赖第三方模块执行方法,比如调用某模块的上传下载,数据库查询等操作的时候,如果出现网络问题或其他问题,可能有超时重新请求的情况;

目前的解决方案有

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 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设计】。

相关文章

Django如何实现网站注册用户邮箱验证功能

Django如何实现网站注册用户邮箱验证功能

我们在很多网站上都可以看到用户注册使用电子邮件激活或启用的方式。也就是说,用户在注册后填写正确的电子邮件地址,接着网站会发送一封启用电子邮件到用户设置的电子邮件的邮箱中,并在邮件中提供一...

python中的常量和变量代码详解

局部和全局变量: # name='lhf' # def change_name(): # # global name # name='帅了一比' # print('cha...

python3 拼接字符串的7种方法

Python的3.0版本,常被称为Python 3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0在设计的时候没有考虑...

在pycharm中显示python画的图方法

在pycharm中显示python画的图方法

问题描述 在电脑中重新安装Anaconda3&PyCharm后,运行原来的程序画图时出现了下图界面。 不能弹出如下图所示的“figure”窗口。 解决方法: 这是因为PyCharm在...

Python运行不显示DOS窗口的解决方法

方法1:pythonw xxx.py 方法2:将.py改成.pyw (这个其实就是使用脚本解析程序pythonw.exe) 跟 python.exe 比较起来,pythonw.exe 有...