If you want to persist certain parameters across multiple requests, you can make use of a session object. This lesson guides you through the process of creating a new session object and how to use it.
The Session Object
Session object allows certain parameters to persist across multiple requests. The TCP connection that gets established will be reused, hence adding performance. When creating a
Session object, it will have the same methods as the main
We’re going to use a context manager—using the statement
with. That’s going to ensure the resources that are used during the session are going to be released after use. So to start that, we’ll say
with requests—here’s where we’re going to create our
Session object. And a very simple name,
Let’s begin by authenticating our
session, and here’s where we’re going to be going to GitHub again. In this case, I’m using my example name—you would put your username for GitHub there—and then I’m going to have it prompt us for the password again.
So now that we’ve created the
Session and set the authentication parameters, instead of
requests.get()… we’ll use
session.get(). So, we’ll save it into
response and here we’re going to grab our user information. And we could have multiple requests—we’ll try that here in a minute.
I’ll make the terminal a little bit larger. What we can see here is after the
Password:, it’s returning back our headers here, the date and the time… And after that, it’s returning JSON with all the information about that response.
Let’s try setting it up with a second request. So, we’ll call this one
response2, and we’ll use the same
session, but we’ll go to a different endpoint here, under
/user, and we’ll look at the
/repos. In fact, let’s print out a specific repo. We’ll say the very, very first repo—repo
0. And we’ll say, “What is the
'url'?”—one of the keys that we can call here.
Become a Member to join the conversation.