加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python自动重试HTTP连接装饰器

发布时间:2020-12-16 20:59:49 所属栏目:Python 来源:网络整理
导读:有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。 这个是python2.7x 的版本,python3.x可以用 nonlocal 来重写。 #-*- coding: utf-8 -*- #all decorators in this tool file #author: orangleliu ##########

有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是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中的装饰器用法详解
  • 详解Python中的装饰器、闭包和functools的教程
  • python 装饰器功能以及函数参数使用介绍
  • python重试装饰器示例
  • Python中的多重装饰器
  • 详解Python装饰器由浅入深
  • Python装饰器decorator用法实例
  • 实例讲解Python编程中@property装饰器的用法
  • Python装饰器原理与简单用法实例分析

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读