python超时重新请求解决方案

作者:百变小超 时间:2022-04-22 00:16:12 

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

目前的解决方案有

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()

来源:https://www.cnblogs.com/dasheng-maritime/p/11602921.html

标签:python,超时,重新,请求,解决
0
投稿

猜你喜欢

  • python中web框架的自定义创建

    2023-09-18 14:54:24
  • 删除数组中重复项(uniq)

    2009-12-28 12:23:00
  • 一些让Python代码简洁的实用技巧总结

    2022-02-06 11:03:25
  • 学习ASP.NET八天入门:第六天

    2007-08-07 13:48:00
  • document.getElementById的简写方式

    2010-06-21 10:44:00
  • Python实现基于SVM的分类器的方法

    2023-11-18 18:20:02
  • 对python使用http、https代理的实例讲解

    2022-03-13 00:03:08
  • js阻止移动端页面滚动的两种方法

    2023-08-04 17:36:12
  • 解决pycharm中opencv-python导入cv2后无法自动补全的问题(不用作任何文件上的修改)

    2023-08-24 00:25:21
  • Flask框架踩坑之ajax跨域请求实现

    2023-12-25 01:28:02
  • python实现将json多行数据传入到mysql中使用

    2022-12-28 06:41:51
  • php 不能连接数据库 php error Can't connect to local MySQL server

    2023-11-07 10:43:50
  • 利用Python复制文件的9种方法总结

    2022-06-25 15:00:27
  • python 通过dict(zip)和{}的方式构造字典的方法

    2023-10-03 00:05:12
  • access MDB 转换为 Execl(ASP类)

    2008-07-19 12:10:00
  • PYTHON基础-时间日期处理小结

    2023-04-23 02:02:59
  • Python Tkinter实例——模拟掷骰子

    2022-09-17 09:51:07
  • Python机器学习性能度量利用鸢尾花数据绘制P-R曲线

    2023-01-27 20:55:48
  • Python爬虫框架NewSpaper使用详解

    2022-06-03 06:20:26
  • PHP将amr音频文件转换为mp3格式的操作细节

    2023-06-15 22:20:35
  • asp之家 网络编程 m.aspxhome.com