This article mainly introduces the Python auto-retry HTTP connection decorator. sometimes we want to go to another interface to retrieve data, which may fail occasionally due to network reasons. in order to automatically retry, we wrote such a decorator, it can be automatically reconnected twice. if you need a friend, you can refer to the following: sometimes we want to go to another interface to retrieve data, and may occasionally fail due to network reasons. in order to automatically retry, write such a decorator.
This is the version of python2.7x, which can be rewritten using nonlocal.
#-*-Coding: UTF-8-*-# all decorators in this tool file # author: orangleliu ####################################### ###################### when an http connection is faulty, automatic reconnection def conn_try_again (function): RETRIES = 0 # Number of RETRIES count = {"num": RETRIES} def wrapped (* args, ** kwargs): try: return function (* args, ** kwargs) except T Exception, err: if count ['num'] <2: count ['num'] + = 1 return wrapped (* args, ** kwargs) else: raise Exception (err) return wrapped
The usage is simple. The following is a program snippet.
@ Conn_try_again def evaluate (self, contract_no, data_month, product_code): # obtain billing data based on the webluker interface. 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 failed t Exception, err: err = U' communication Exception between webluker interface 'raise Exception (err)
If an exception occurs in the try block, the system automatically retries twice.