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次。