Python自动重试HTTP连接装饰器

(编辑:jimmy 日期: 2024/10/3 浏览:2)

有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是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次。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。