Python automatically retries HTTP connection decorator

Source: Internet
Author: User
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.

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.