Python automatically retries HTTP connection adorner

Source: Internet
Author: User

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.