python requests library redirect

Python Requests Library Redirect

If you are using the Python Requests library to send HTTP requests to a web server, you may encounter situations where the server responds with a redirect response (HTTP status code 3xx).

When a redirect response is received, the Requests library can automatically follow the redirect and retrieve the resource from the new location. This behavior is controlled by the allow_redirects parameter of the request() method.

Following Redirects

The simplest way to follow redirects is to set allow_redirects to True:


import requests

response = requests.get('http://example.com', allow_redirects=True)

print(response.status_code)
print(response.history)
print(response.url)
  

The history property of the response object contains a list of all responses that were followed to get to the final response. If there were no redirects, this list will be empty.

Limiting Redirects

If you want to limit the number of redirects that the Requests library will follow, you can set the max_redirects parameter. For example, to allow only one redirect:


import requests

response = requests.get('http://example.com', allow_redirects=True, max_redirects=1)

print(response.status_code)
print(response.history)
print(response.url)
  

If there are more redirects than the specified limit, the library will raise a TooManyRedirects exception.

Disabling Redirects

If you want to disable redirects entirely, you can set allow_redirects to False:


import requests

response = requests.get('http://example.com', allow_redirects=False)

print(response.status_code)
print(response.history)
print(response.url)
  

In this case, the response object will contain the redirect response instead of following the redirect.

That's it for this tutorial on using the Python Requests library to handle redirects. By controlling the allow_redirects and max_redirects parameters, you can customize how the library handles redirects and retrieve the resources you need.