does python requests follow redirects

Does Python Requests Follow Redirects?

Yes, Python Requests follow redirects by default. When the server responds with a redirect status code, Python Requests automatically follows the redirection.

For example, if a server returns a 302 status code (Found), it indicates that the requested resource has been temporarily moved to a different URL. In this case, Python Requests will automatically send a new request to the new URL.

How to Disable Redirects in Python Requests

If you want to disable redirects in Python Requests, you can set the allow_redirects parameter to False when making a request:


import requests

response = requests.get('https://www.example.com', allow_redirects=False)
print(response.status_code)

In this case, if the server returns a redirect status code, Python Requests will raise a requests.exceptions.Redirect exception.

How to Handle Redirects Manually in Python Requests

If you want to handle redirects manually in Python Requests, you can set the allow_redirects parameter to True (the default value) and use the history attribute of the response object:


import requests

response = requests.get('https://www.example.com')
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

In this case, if the server returns a redirect status code, Python Requests will follow the redirection and the response object will contain the entire redirect history. You can access the redirect history using the history attribute of the response object.