[Python] An adorner that shares an HTTP connection retry

Source: Internet
Author: User

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

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.