Python Retry Library: Checking Retry Count for Decorated Functions
The retry count of a function decorated by the retrying library in Python can be checked by accessing the 'last_attempt' property of the 'RetryCallState' object passed to the 'retry_error_callback' function.
Here's an example:
import retrying
@retrying.retry(wait_fixed=1000, stop_max_attempt_number=3, retry_on_exception=retrying.retry_if_exception_type(RuntimeError))
def my_func():
print('Trying...')
raise RuntimeError('Something went wrong')
def retry_error_callback(exception, delay):
print(f'Retrying after {delay} seconds...')
print(f'Retry count: {exception.last_attempt.attempt_number}')
try:
my_func()
except RuntimeError as e:
print('Error:', e)
In the above example, the 'my_func' function is decorated with the 'retrying' library, which will retry the function call up to 3 times if a 'RuntimeError' exception is raised. The 'retry_error_callback' function is passed as a parameter to the 'retry' decorator, which will be called on each retry attempt.
Inside the 'retry_error_callback' function, the 'last_attempt' property of the 'exception' object is accessed to get the current retry count.
When you run this code, you should see output similar to the following:
Trying...
Retry count: 1
Trying...
Retry count: 2
Trying...
Error: Something went wrong
原文地址: https://www.cveoy.top/t/topic/nDH6 著作权归作者所有。请勿转载和采集!