python requests library follow redirect

Python Requests Library Follow Redirect

If you are working with Python Requests library and need to follow redirects, it's very simple. By default, Requests will perform a maximum of 30 redirects before it gives up. However, you can set the maximum number of redirects to follow by setting the allow_redirects parameter to True.

Here's an example:


import requests

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

print(response.content)

In the code above, we have imported the requests library and used the get() method to make a request to "http://example.com". By setting the allow_redirects parameter to True, Requests will automatically follow any redirects that occur.

Handling Redirects Manually

Sometimes, you might want to handle redirects manually. In this case, you can set the allow_redirects parameter to False and check for any redirects yourself using the is_redirect attribute of the response object.


import requests

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

if response.is_redirect:
    redirected_url = response.headers['location']
    response = requests.get(redirected_url)

print(response.content)

In the code above, we have set allow_redirects to False and checked if the response is a redirect using the is_redirect attribute. If it is, we get the redirected URL from the location header and make another request to that URL.

Conclusion

Python Requests library makes it easy to follow redirects. You can either let Requests handle redirects automatically or handle them manually. Hopefully, this tutorial has helped you understand how to use the allow_redirects parameter in Requests.