Juan Carlos Coto
Juan Carlos Coto

Reputation: 12564

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!

Upvotes: 5

Views: 6940

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122092

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.

Upvotes: 12

Related Questions