Python自动重试HTTP连接装饰器

yipeiwu_com6年前Python基础

有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是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操作Sonqube API获取检测结果并打印过程解析

这篇文章主要介绍了Python操作Sonqube API获取检测结果并打印过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1....

python 字符串常用方法汇总详解

1.字符串大小写转 value = "wangdianchao" # 转换为大写 big_value = value.upper() print(big_value) # 转换为小写...

python try 异常处理(史上最全)

在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!! 有时候我们写程序的时候,会出现一些错误或异常,导致程序终止. 为了处理异常,...

独特的python循环语句

1、局部变量 for i in range(5): print i, print i, 运行结果: 0 1 2 3 4 4 i是for语句里面的局部变量。但在python...

详谈Pandas中iloc和loc以及ix的区别

Pandas库中有iloc和loc以及ix可以用来索引数据,抽取数据。但是方法一多也容易造成混淆。下面将一一来结合代码说清其中的区别。 1. iloc和loc的区别: iloc主要使用数...