Original link: https://www.kingname.info/2023/06/11/retry-in-requests/
Programmers are a group that needs continuous learning. If you find that the code you write now is no different from the code you wrote 5 years ago, it means you have fallen behind.
When we do Python development, we often use some third-party libraries, which have continued to add new functions for many years. But I found that many students will not use new functions at all when using these third-party libraries. Their code is the same as it was a few years ago.
For example, use Request to initiate an HTTP request. When the request fails, no matter what the reason is, retry up to 3 times in place. Many people mainly have the following three ways of writing to try again.
common old way
Use third-party libraries
Such students will use some third-party libraries that specialize in retrying, such as tenacity. See my article for details: Tenacity——Exception Retry has never been easier
Manually write decorators
This kind of students will use decorators, so they usually write decorators by hand to reuse them, for example:
1 |
def retry ( func ): |
repeated for loop
There are also some students who write code in a wild way:
1 |
def login (): |
Such students basically do not reuse code. In the code, if requests are made to N urls, they will write codes like the above in N places.
new method
Although I am talking about a new method here, this method should have been available at least 9 years ago. It’s just that fewer people use it online. We can use HTTPAdapter
that comes with requests to implement automatic retry. This method can be used when we don’t care what the specific error is and just need to retry mechanically:
1 |
import requests |
This article is transferred from: https://www.kingname.info/2023/06/11/retry-in-requests/
This site is only for collection, and the copyright belongs to the original author.