Session Objects

The Session object allows you 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 you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

A Session object has all the methods of the main Requests API.

Let’s persist some cookies across requests:

  1. s = requests.Session()
  2. s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
  3. r = s.get('http://httpbin.org/cookies')
  4. print(r.text)
  5. # '{"cookies": {"sessioncookie": "123456789"}}'

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:

  1. s = requests.Session()
  2. s.auth = ('user', 'pass')
  3. s.headers.update({'x-test': 'true'})
  4. # both 'x-test' and 'x-test2' are sent
  5. s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

Any dictionaries that you pass to a request method will be merged with the session-level values that are set. The method-level parameters override session parameters.

Note, however, that method-level parameters will not be persisted across requests, even if using a session. This example will only send the cookies with the first request, but not the second:

  1. s = requests.Session()
  2. r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
  3. print(r.text)
  4. # '{"cookies": {"from-my": "browser"}}'
  5. r = s.get('http://httpbin.org/cookies')
  6. print(r.text)
  7. # '{"cookies": {}}'

If you want to manually add cookies to your session, use the Cookie utility functions to manipulate Session.cookies.

Sessions can also be used as context managers:

  1. with requests.Session() as s:
  2. s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')

This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.

Remove a Value From a Dict Parameter

Sometimes you’ll want to omit session-level keys from a dict parameter. To do this, you simply set that key’s value to None in the method-level parameter. It will automatically be omitted.

All values that are contained within a session are directly available to you. See the Session API Docs to learn more.