Python自动重试HTTP连接装饰器

yipeiwu_com5年前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获取程序执行文件路径的方法(推荐)

python获取程序执行文件路径的方法(推荐)

1.获取当前执行主脚本方法:sys.argv[0]和_ file _ (1)sys.argv 一个传给Python脚本的指令参数列表。sys.argv[0]是脚本的名字。一般得到的是...

Python使用os模块和fileinput模块来操作文件目录

os模块 在python编程中,我们会经常使用到文件和目录,这些操作python提供一个os模块,里面有很多操作文件和目录的函数. 下面介绍os的常用功能 1.获取当前路径 >...

Python使用import导入本地脚本及导入模块的技巧总结

本文实例讲述了Python使用import导入本地脚本及导入模块的技巧。分享给大家供大家参考,具体如下: 导入本地脚本 import 如果你要导入的 Python 脚本与当前脚本位于同一...

python 多个参数不为空校验方法

在实际开发中经常需要对前端传递的多个参数进行不为空校验,可以使用python提供的all()函数 if not all([arg1, arg2, arg3]): # 当 arg1,...

python+opencv实现动态物体识别

python+opencv实现动态物体识别

注意:这种方法十分受光线变化影响 自己在家拿着手机瞎晃的成果图: 源代码: # -*- coding: utf-8 -*- """ Created on Wed Sep 2...