Python自动重试HTTP连接装饰器
有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是python2.7x的版本,python3.x可以用nonlocal来重写。
#-*-coding:utf-8-*-
#alldecoratorsinthistoolfile
#author:orangleliu
############################################################
#http连接有问题时候,自动重连
defconn_try_again(function):
RETRIES=0
#重试的次数
count={"num":RETRIES}
defwrapped(*args,**kwargs):
try:
returnfunction(*args,**kwargs)
exceptException,err:
ifcount['num']<2:
count['num']+=1
returnwrapped(*args,**kwargs)
else:
raiseException(err)
returnwrapped
用法很的简单,下面是一个程序片段。
@conn_try_again
defpost_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()
ifnotbilldata:
billdata={}
returnbilldata
exceptException,err:
err=u'与webluker接口间通信异常'
raiseException(err)
如果try块中有异常,就会自动重试2次。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下