python超时重新请求解决方案
2019-10-21 18:05
2016 查看
在应用中,有时候会 依赖第三方模块执行方法,比如调用某模块的上传下载,数据库查询等操作的时候,如果出现网络问题或其他问题,可能有超时重新请求的情况;
目前的解决方案有
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()
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- SQL SERVER错误:已超过了锁请求超时时段。 (Microsoft SQL Server,错误: 1222) 解决方案
- Ajax请求超时解决方案:
- 详解python使用pip安装第三方库(工具包)速度慢、超时、失败的解决方案
- HttpWebRequest请求超时异常的处理方法(重新发送请求到成功为止)
- python以gzip header请求html数据时,response内容乱码无法解码的解决方案
- Ext下,ajax请求和普通http请求,session超时转到登录页面的解决方案
- curl或wget 请求服务器超时 504解决方案
- HttpWebRequest请求超时的解决方案!
- iOS 对于下载请求超时重新下载的方法
- iframe请求失效重新登录后直接跳转到请求内容页面的解决方案
- python以gzip header请求html数据时,response内容乱码无法解码的解决方案
- ping github 请求超时解决方案
- python使用vps重新拨号之后出现连接mongoDB超时的处理
- Ext下,ajax请求和普通http请求,session超时转到登录页面的解决方案
- axios请求超时自动重新请求
- webClient请求JAVA超时解决方案
- 微信公众号 请求url超时解决方案
- ASP.NET Core MVC请求超时设置解决方案
- HttpException (0x80004005): 请求已超时的解决方案
- axios的超时重新请求