Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid / prevent Max Redirects error with requests in Python?

Trying to avoid getting a Number of Redirects Exceeds 30 error with python-requests. Is there something I can do to avoid it, or is it purely server-side? I got this error while trying to GET facebook.com.

Thanks very much!

like image 672
Juan Carlos Coto Avatar asked Dec 15 '22 10:12

Juan Carlos Coto


1 Answers

The server is redirecting you in a loop. You'll need to figure out why you are being redirected so often.

You could try to see what goes on by not allowing redirects (set allow_redirects=False), then resolving them using the .resolve_redirects() API:

>>> import requests
>>> url = 'http://httpbin.org/redirect/5'  # redirects 5 times
>>> session = requests.session()
>>> r = session.get(url, allow_redirects=False)
>>> r.headers.get('location')
'/redirect/4'
>>> for redirect in session.resolve_redirects(r, r.request):
...     print redirect.headers.get('location')
... 
/redirect/3
/redirect/2
/redirect/1
/get
None

The redirect objects are proper responses; print out from these what you need to figure out why you end up in a redirect loop; perhaps the server is providing clues in the headers or the body.

like image 108
Martijn Pieters Avatar answered Dec 18 '22 10:12

Martijn Pieters