[ad_1]
Since Tenacity’s official web site solely presents a easy API doc, let’s begin with the library’s set up and a few primary utilization.
Set up
For those who’re utilizing pip, merely run the next:
python -m pip set up tenacity
For those who’re utilizing Anaconda, Tenacity is just not within the default channel, so you must set up it from conda-forge
:
conda set up -c conda-forge tenacity
Fundamental utilization
After putting in Tenacity, let’s have a look at some primary utilization of the library.
Merely add an @retry
decorator and your code may have retry capabilities:
@retry()
async def coro_func():
move
In order for you your code to cease retrying after a sure variety of makes an attempt, you possibly can write it like this:
@retry(cease=stop_after_attempt(5))
async def coro_func():
move
After all, to keep away from frequent retries which will exhaust connection swimming pools, I like to recommend including a ready time earlier than every retry. For instance, if you wish to wait for two seconds earlier than every connection:
@retry(wait=wait_fixed(2))
async def coro_func():
move
Though it’s not talked about within the documentation, I choose to attend an additional second longer than the final time earlier than every retry to attenuate useful resource waste:
@retry(wait=wait_incrementing(begin=1, increment=1, max=5))
async def coro_func():
move
Lastly, if the retry is brought on by an exception
being thrown within the methodology, it’s best to throw the exception
again out. This enables for extra versatile exception dealing with when calling the strategy:
@retry(reraise=True, cease=stop_after_attempt(3))
async def coro_func():
move
[ad_2]