Redirection and History

By default Requests will perform location redirection for all verbs except HEAD.

We can use the history property of the Response object to track redirection.

The Response.history list contains the Response objects that were created in order to complete the request. The list is sorted from the oldest to the most recent response.

For example, GitHub redirects all HTTP requests to HTTPS:

  1. >>> r = requests.get('http://github.com')
  2. >>> r.url
  3. 'https://github.com/'
  4. >>> r.status_code
  5. 200
  6. >>> r.history
  7. [<Response [301]>]

If you’re using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable redirection handling with the allow_redirects parameter:

  1. >>> r = requests.get('http://github.com', allow_redirects=False)
  2. >>> r.status_code
  3. 301
  4. >>> r.history
  5. []

If you’re using HEAD, you can enable redirection as well:

  1. >>> r = requests.head('http://github.com', allow_redirects=True)
  2. >>> r.url
  3. 'https://github.com/'
  4. >>> r.history
  5. [<Response [301]>]