Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of retrying retry Mechanism in Python

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of the retrying retry mechanism in Python, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

Cyclic addition judgment

The easiest way to retry is to add a loop to the code snippet that needs to be retried, catch an exception in the program, exit the loop if the execution succeeds, and repeat the relevant code if the execution fails, for example:

Import requestsdef req_with_retry (url): retry_max = 10 # the maximum number of retries is 10 for i in range (1, retry_max+1): try: print ("the {} request" .format (I)) # here the ConnectTimeout exception will be thrown res = requests.get (url) Timeout=1) data = res.json () print ("request succeeded:", data) break except requests.exceptions.ConnectTimeout as e: continue# requests a non-existent URL req_with_retry (https://www..cn/))

Execution result:

Because a URL that does not exist has been requested, I have been retrying until the maximum number of times has been reached 10 times. But this has a certain degree of code intrusiveness, adding loop judgment to the business logic is very unattractive, don't worry, look down, there are better ways.

Retrying

Retrying is a third-party library of Python, which provides a decorator function retry. The decorated business function will be reexecuted under the condition of failure. By default, whenever an error is reported, it will keep retrying until the execution is successful.

You can use pip install retrying for installation.

For example, in the following code, we use the size of the generated random number to simulate the success and failure of the business. As long as the generated random number is greater than 2, it will be regarded as a failure and will try again until the generated random number is less than 2:

Import randomfrom retrying import retry@retrydef random_with_retry (): if random.randint (0,10) > 2: print ("> 2, try again...") Raise Exception ("greater than 2") print ("less than 2, successful!") Random_with_retry ()

The running results are as follows:

Retry can also accept some parameters. Here are the optional parameters in the initialization function of the Retrying class in the source code:

Stop_max_attempt_number: the maximum number of retries, after which the retry is stopped

Stop_max_delay: maximum delay time (the total time it takes to execute this method retry), after which it stops

Wait_fixed: the waiting time between two retrying

Wait_random_min and wait_random_max: generate the wait time between two retrying randomly

Wait_incrementing_start and wait_incrementing_increment: increase the fixed duration for each call

Wait_exponential_multiplier and wait_exponential_max: the wait time between two retrying is generated exponentially, and the value generated is 2 ^ waiting _ attempt_number * wait_exponential_multiplier,previous_attempt_number is the number of times that the previous retry has been generated. If the resulting value exceeds the size of the wait_exponential_max, then the pause value between the two retrying is wait_exponential_max.

Of particular note is the retry_on_exception parameter, which receives a function and is used as follows:

# judging exception def is_MyError (exception): print ("judging exception", exception) print (isinstance (exception, (ValueError, IOError, ConnectionError)) return isinstance (exception, (ValueError, IOError, ConnectionError)) @ retry (retry_on_exception=is_MyError) def random_with_retry (): "" A random integer before 0-10 is greater than 2. Throw an exception. Less than 2 success: return: "" if random.randint (0,10) > 2: print ("greater than 2, try again.") Raise ValueError ("greater than 2") print ("less than 2, successful!") Random_with_retry ()

The general idea of the retry_on_exception parameter here is: receive a custom function is_MyError, and determine whether it belongs to ValueError, IOError, and ConnectionError in the is_MyError function; if the random_with_retry () function throws an exception, it will go to the function is_MyError () to determine whether the return is True or False, if it is True, continue to try again, if it is False, stop immediately and throw an exception.

There is also the retry_on_result parameter, which also receives a function to determine which results the business function returns and needs to be retried, similar to the retry_on_exception parameter.

We can match these parameters reasonably according to our own needs to achieve the effect we want.

Thank you for reading this article carefully. I hope the article "sample Analysis of retrying retry Mechanism in Python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 282

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report