Python'stenacity
The library is used to implement retry mechanisms, which are particularly suitable for handling function call failures caused by network instability or other unexpected errors. The following is a brief introduction to its main components, as well as practical application examples and corresponding code.
Component Description
-
retry: Decorator, used to mark functions that need to be retryed. When the function throws an exception,
tenacity
It will automatically retry according to the set policy. -
stop_after_attempt(n): Set the maximum number of retry times, parameters
n
Indicates that the number of times is reached will stop retry. For example,stop_after_attempt(3)
Indicates that you try again up to three times. -
wait_fixed(seconds): Set a fixed waiting time between each retry, parameters
seconds
Specifies the number of seconds to wait. For example,wait_fixed(2)
Indicates waiting for two seconds before each retry.
Example of usage
Here is a simple example showing how to use these components:
from tenacity import retry, stop_after_attempt, wait_fixed @retry(stop=stop_after_attempt(3), wait=wait_fixed(2)) def test_function(): print("Try to execute...") raise Exception("An error occurred") if __name__ == '__main__': try: test_function() except Exception as e: print(f"Final failure: {e}")
In this example,test_function
Decorated to retry up to three times when an exception occurs, waiting for two seconds between each retry. If it still fails after three attempts, the program will capture and print the final error message.
Practical application scenarios
1. Network request:
When making an API call, if the request fails (for example due to network problems), you can usetenacity
Automatically try again.
Sample code:
import requests from tenacity import retry, stop_after_attempt, wait_fixed @retry(stop=stop_after_attempt(5), wait=wait_fixed(3)) def fetch_data(url): response = (url) response.raise_for_status() # If the response status code is not 200, an exception will be thrown return () url = "/data" try: data = fetch_data(url) print("Data acquisition successfully:", data) except Exception as e: print(f"Data acquisition failed: {e}")
2. File operation:
- When reading or writing a file, if you encounter a temporary error (such as the file being occupied), you can try again to increase your chances of success.
- Sample code:
from tenacity import retry, stop_after_attempt, wait_fixed @retry(stop=stop_after_attempt(3), wait=wait_fixed(1)) def read_file(file_path): with open(file_path, 'r') as file: return () try: content = read_file("") print("File Content:", content) except Exception as e: print(f"Failed to read the file: {e}")
3. Database operations:
- When doing a database transaction, if it fails due to a connection problem, you can use this mechanism to try again.
- Sample code:
import sqlite3 from tenacity import retry, stop_after_attempt, wait_fixed @retry(stop=stop_after_attempt(3), wait=wait_fixed(2)) def execute_query(query): conn = ('') cursor = () (query) () () try: execute_query("INSERT INTO users (name) VALUES ('Alice')") print("Insert successfully") except Exception as e: print(f"Database operation failed: {e}")
By usingtenacity
The library can effectively improve the robustness of the program and reduce failures caused by temporary errors. These practical application scenarios show how to use this library to deal with unstable factors in daily programming, thereby improving user experience and system stability.
This is the end of this article about Python's detailed explanation of the timeout retry mechanism using the tenacity library. For more related content of the Python tenacity retry mechanism, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!