requests
handles redirects for you, see redirection and history.
Set allow_redirects=False
if you don't want requests
to handle redirections, or you can inspect the redirection responses contained in the r.history
list.
Demo:
>>> import requests
>>> url = 'https://httpbin.org/redirect-to'
>>> params = {"status_code": 301, "url": "https://mcmap.net/q/395856/-http-redirection-code-3xx-in-python-requests"}
>>> r = requests.get(url, params=params)
>>> r.history
[<Response [301]>, <Response [302]>]
>>> r.history[0].status_code
301
>>> r.history[0].headers['Location']
'https://mcmap.net/q/395856/-http-redirection-code-3xx-in-python-requests'
>>> r.url
'https://mcmap.net/q/395856/-http-redirection-code-3xx-in-python-requests'
>>> r = requests.get(url, params=params, allow_redirects=False)
>>> r.status_code
301
>>> r.url
'https://httpbin.org/redirect-to?status_code=301&url=https%3A%2F%2Fstackoverflow.com%2Fq%2F22150023'
So if allow_redirects
is True
, the redirects have been followed and the final response returned is the final page after following redirects. If allow_redirects
is False
, the first response is returned, even if it is a redirect.