This article mainly introduces the Python automatic retry HTTP connection Adorner, sometimes we have to go to other interfaces to fetch data, perhaps because the network reason occasionally failed, in order to be able to automatically retry, wrote such an adorner, can realize automatic reconnection 2 times, need friends can refer to
Sometimes we have to go to other interfaces to fetch data, perhaps because the network reason occasionally fails, in order to be able to automatically retry, wrote such an adorner.
This is the python2.7x version, python3.x can be rewritten with nonlocal.
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20 |
#-*-coding:utf-8-*-#all Decorators in this tool file #author: Orangleliu ########################################### ################# #http连接有问题时候, automatic ligature 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 R Eturn Wrapped (*args, **kwargs) else:raise Exception (err) return wrapped |
The usage is very simple, the following is a program fragment.
?
| 1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15 |
@conn_try_again def post_query_bandwidth_for_bandwidth (self, contract_no, Data_month, product_code): # Obtain billing data according to 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.re AD () if not billdata:billdata = {} return billdata except Exception, Err:err = U ' communication with Webluker interface exception ' raise Exception (ERR) |
If there is an exception in the try block, it is automatically retried 2 times.