python requests module redirects

Python Requests Module Redirects

Redirects are common in web applications. There are situations where a web page redirects to another page. Python provides the Requests module that can be used to work with HTTP requests and responses. The Requests module provides an easy-to-use interface for sending HTTP requests and handling responses.

Redirecting HTTP Requests with Requests Module

Redirects in the Requests module can be handled easily using the following code:

import requests

url = 'https://www.example.com'

response = requests.get(url)

print(response.url)

print(response.history)

In the above code, we first import the Requests module. Then, we define the URL that we want to access. We use the get() method to send an HTTP GET request to the URL. The response object returned by get() method contains information about the request and response. We can access the URL of the response using response.url property. If the request is redirected, then the history list property of response object will contain Response objects for all the redirects.

Handling Redirects in Requests Module

The Requests module automatically handles redirects by default. However, we can disable this behavior using the allow_redirects parameter of requests.get() method. The value of allow_redirects parameter must be set to False, as shown below:

import requests

url = 'https://www.example.com'

response = requests.get(url, allow_redirects=False)

print(response.status_code)

In the above code, we set allow_redirects parameter to False, which means that if the URL redirects, then the response will contain a status code of 302 instead of redirecting to the new URL.

Following Redirects in Requests Module

If we want to follow the redirects, we can set allow_redirects parameter to True (default value). The following code demonstrates how to follow redirects:

import requests

url = 'https://www.example.com'

response = requests.get(url, allow_redirects=True)

print(response.url)

print(response.history)

In the above code, we set allow_redirects parameter to True. If the URL redirects, then the final URL will be returned in response.url property. The history list property of response object will contain Response objects for all the redirects.

Conclusion

The Requests module in Python makes it easy to send HTTP requests and handle responses. Redirects can be handled easily using the Requests module. We can follow or disable redirects using allow_redirects parameter of requests.get() method.