Sometimes we have to go to other interfaces to fetch data, possibly because the network reason occasionally failed, in order to be able to automatically retry, wrote such an adorner.
This is the version of python2.7x, python3.x can be rewritten with nonlocal.
#-*-coding:utf-8-*-#all decorators in this tool file#author:orangleliu############################################# ############### #http连接有问题时候, Auto-re-connect 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
The usage is very simple, here is a program fragment.
@conn_try_again def post_query_bandwidth_for_bandwidth (self, contract_no, Data_month, product_code): # Get billing data based on Webluker interface try: post_data = {' contract ': contract_no, ' month ': Data_month, ' Code ':p Roduct_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 ' Communication exception between Webluker interface ' raise Exception (ERR)
If there is an exception in the try block, it is automatically retried 2 times.
This article is derived from "Orangleliu notebook " Blog, be sure to keep this source http://blog.csdn.net/orangleliu/article/details/39226319
[Python] An adorner that shares an HTTP connection retry