In the next three lessons you’ll have a closer look at performance of requests. Therefore, the following three things are covered:
- The Session Object
- Max Retries
This lesson covers Timeouts.
timeout is a parameter of how long we’re going to wait for a response before moving on. The default for
requests is to wait indefinitely. With the
timeout parameter, you can set an amount of time in seconds, and that value can be either an integer or a float. A tuple could be used—the first value would be how long to establish the connection, and the second would be how long to wait for the response. Let’s check it out.
Let’s just set it to
1 second and see what that does. All right! Successful. We waited up to a second and the moment it had the response, it no longer was waiting. What if we set something too low?
If we create a
timeout that’s much too low—like, let’s say one thousandth of a second—what happens? So, we’re going to be super impatient here. In this case… it caused a
ConnectTimeoutError. The connection to
api.github.com timed out with this very low
timeout value, so it raised an exception—the
ConnectTimeout exception. Let’s try it again.
Let’s go with a hundredth of a second. Oh, same. Too impatient. How about just a tenth of a second? Okay. So, how about half a second? Okay. So, in this particular case with my current internet connection and what’s going on, a half second seems be a long enough
You may want to leave a little bit more—
2 seconds might be a good value. As you can see, it didn’t wait two seconds to finish it—it’s just, “When will it time out?” So in the intro, I talked about setting up a tuple to designate the amount of time that we’re going to establish the connection, and the second is to wait for the response.
Ope, got to spell
requests. There we go. Success. For these errors, instead of getting this very verbose error here, we could also set up a section in our code to print out something that’s a little more readable in the console. Let’s try that out.
For this file, I’m going to name it
timeout.py. Exit my REPL. So, for the script we’ll import
requests first, and then from
requests.exceptions we’ll import
Timeout. We’ll set up a
Become a Member to join the conversation.