Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Session Objects – Python requests

  • Last Updated : 05 Mar, 2020

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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


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:

# 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(' / headers', headers ={'x-test2': 'true'})
# print object


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!