Python自动重试HTTP连接装饰器
作者:junjie 时间:2022-02-18 12:55:55
有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是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,连接,装饰器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp脚本延时 自定义的delay函数
2008-04-07 12:59:00
python通过http上传文件思路详解
2022-02-08 12:48:30
![](https://img.aspxhome.com/file/2023/9/79419_0s.png)
django restframework serializer 增加自定义字段操作
2023-12-17 20:36:10
Python切片用法实例教程
2023-09-28 15:26:17
python进阶之自定义可迭代的类
2022-09-20 10:18:48
JavaScript如何获取一个元素的样式信息
2023-08-28 12:16:17
SQL查询入门(中篇)
2011-09-30 11:15:09
python logging添加filter教程
2022-08-21 00:36:43
教你快速掌握两个SQL Server的维护技巧
2009-01-15 13:31:00
如何使用python-opencv批量生成带噪点噪线的数字验证码
2023-10-14 03:38:54
![](https://img.aspxhome.com/file/2023/2/92212_0s.png)
Python实现用手机监控远程控制电脑的方法
2021-06-22 07:57:49
PHP实现批量生成App各种尺寸Logo
2023-07-23 03:59:59
对Django的restful用法详解(自带的增删改查)
2023-11-12 07:45:04
![](https://img.aspxhome.com/file/2023/8/110228_0s.jpg)
关于Python解包知识点总结
2021-01-03 22:34:15
Jquery中Ajax 缓存带来的影响的解决方法
2011-05-21 16:14:00
网页表单项Input的高级限制级用法
2008-10-27 16:50:00
Python PaddleNLP开源实现快递单信息抽取
2023-01-21 04:35:11
![](https://img.aspxhome.com/file/2023/3/80603_0s.jpg)
Dreamweaver基础技巧全面接触
2010-03-25 12:23:00
![](https://img.aspxhome.com/file/UploadPic/20071/2007131103144537s.gif)
基于Python socket的端口扫描程序实例代码
2021-02-24 03:05:09
推荐个辅助软件FastStone Capture
2008-12-23 13:23:00
![](https://img.aspxhome.com/file/UploadPic/200812/23/screenruler1-61s.jpg)