Python自动重试HTTP连接装饰器
2019/7/13 21:20:32
本文主要是介绍Python自动重试HTTP连接装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是python2.7x 的版本,python3.x可以用 nonlocal 来重写。
#-*- coding: utf-8 -*- #all decorators in this tool file #author: orangleliu ############################################################ #http连接有问题时候,自动重连 def conn_try_again(function): RETRIES = 0 #重试的次数 count = {"num": RETRIES} def wrapped(*args, **kwargs): try: return function(*args, **kwargs) except Exception, err: if count['num'] < 2: count['num'] += 1 return wrapped(*args, **kwargs) else: raise Exception(err) return wrapped
用法很的简单,下面是一个程序片段。
@conn_try_again def post_query_bandwidth_for_bandwidth(self, contract_no, data_month, product_code): #根据webluker接口情况获取计费数据 try: post_data = {'contract':contract_no, 'month': data_month, 'code':product_code} params = urllib.urlencode(post_data) response = urllib2.urlopen(WEBLUKER_BANDWITH_API + "?" +params) billdata = {} billdata = response.read() if not billdata: billdata = {} return billdata except Exception, err: err = u'与webluker接口间通信异常' raise Exception(err)
如果try块中有异常,就会自动重试2次。
这篇关于Python自动重试HTTP连接装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python