Python Requests Follow Redirect False
When making HTTP requests in Python using the requests library, you may come across situations where the server returns a redirect response with a different URL. By default, requests automatically follows these redirects. However, if you want to disable this behavior and handle redirects manually, you can use the allow_redirects
parameter and set it to False
.
Example:
import requests
response = requests.get('https://www.example.com', allow_redirects=False)
print(response.status_code)
In this example, we are making a GET request to https://www.example.com
and setting the allow_redirects
parameter to False
. This means that if the server returns a redirect response, requests will not follow it and instead return the redirect response back to the client.
If you want to handle the redirect manually and follow it yourself, you can set allow_redirects
to True
and use the next
attribute of the response object to get the redirected URL.
Example:
import requests
response = requests.get('https://www.example.com', allow_redirects=True)
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 example, we are again making a GET request to https://www.example.com
, but this time setting allow_redirects
to True
. If the server returns a redirect response, the response.history
attribute will contain a list of all the redirect responses. We can use this to print out the status codes and URLs of all the redirects, as well as the final destination URL.
Overall, the allow_redirects
parameter in requests provides a simple way to handle redirects in your Python code. Whether you want to follow redirects automatically or handle them manually, requests has you covered.