Session Objects – Python requests

Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase. A session object all the methods as of requests.

Using Session Objects

Let us illustrate use of session objects by setting a cookie to a url and then making a request again to check if cookie is set.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import requests module
import requests
  
# create a session object
s = requests.Session()
  
# make a get request
s.get('https://httpbin.org / cookies / set / sessioncookie / 123456789')
  
# again make a get request
r = s.get('https://httpbin.org / cookies')
  
# check if cookie is still set
print(r.text)

chevron_right



Output

session-objects-python-requests
One can check that cookie was still set when the request was made again.
Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object:

filter_none

edit
close

play_arrow

link
brightness_4
code

# import requests module
import requests
  
# create a session object
s = requests.Session()
  
# set username and password
s.auth = ('user', 'pass')
  
# update headers
s.headers.update({'x-test': 'true'})
  
# both 'x-test' and 'x-test2' are sent
s.get('https://httpbin.org / headers', headers ={'x-test2': 'true'})
  
# print object
print(s)

chevron_right


Output
session-object-pytohn-requests




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.