python requests post follow redirect

Python Requests Post Follow Redirect

When using Python requests library, sometimes we encounter situations when we send a POST request and it is redirected to another URL. In such cases, we need to follow the redirect and make the request to the new URL. In this PAA, we will see how to handle this scenario using requests.post() function.

Example Scenario

Suppose we want to make a POST request to a website and the request is redirected to a different URL. Here is an example:


import requests

url = 'http://example.com/login'
data = {'username': 'john', 'password': 'doe'}

response = requests.post(url, data=data)

print(response.url)

In this example, we are making a POST request to the URL 'http://example.com/login' with username and password data. However, if the website has a redirect configured for this URL, our request will be redirected to a different URL. To follow the redirect, we need to use the allow_redirects parameter.

Using allow_redirects Parameter

The allow_redirects parameter in requests.post() function controls whether to allow redirects or not. By default, it is set to True, which means that redirects are allowed. To disable redirects, we can set it to False.

Here is an updated example that follows the redirect:


import requests

url = 'http://example.com/login'
data = {'username': 'john', 'password': 'doe'}

response = requests.post(url, data=data, allow_redirects=True)

print(response.url)

In this example, we have set the allow_redirects parameter to True, which means that we want to follow the redirect. After the request is made, the response.url attribute will give us the final URL after following the redirect.

Using Session Object

Another way to handle redirects is by using a session object instead of making individual requests. A session object allows us to persist certain parameters across requests, such as cookies and headers. This can be useful in scenarios where we need to make multiple requests to the same website.

Here is an example:


import requests

url = 'http://example.com/login'
data = {'username': 'john', 'password': 'doe'}

session = requests.Session()
response = session.post(url, data=data)

print(response.url)

In this example, we are using a session object to make the request. When the response is redirected, the session object automatically follows the redirect and makes the request to the new URL. The response.url attribute will give us the final URL.

Conclusion

In this PAA, we have seen how to handle redirects when making a POST request using Python requests library. We can either use the allow_redirects parameter or a session object to follow the redirect and obtain the final URL.