• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python自动重试HTTP连接装饰器

python 搞代码 4年前 (2022-01-09) 14次浏览 已收录 0个评论

有时候我们要去别的接口取数据,可能因为网络原因偶尔失败,为了能自动重试,写了这么一个装饰器。
这个是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'与web<em>本文来源[email protected]搞@^&代*@码)网5</em>luker接口间通信异常'     raise Exception(err) 

如果try块中有异常,就会自动重试2次。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python自动重试HTTP连接装饰器
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址