Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-requests: Limit Number of Redirects Followed

Is there a way to limit the number of redirects that python-requests will follow when performing a GET?

I know about allow_redirects=False, but that just prevents redirects all together. I'm looking for a way to follow redirects, up to some maximum number of hops.

# What I know how to do:
resp = requests.get(url)  # follows redirects "infinitely"
resp = requests.get(url, allow_redirects=False)  # follows no redirects

# What I'm trying to do:
resp = requests.get(url, max_redirects=3)  # follow up to 3 redirects

Thanks!

like image 684
ron rothman Avatar asked Jul 22 '15 01:07

ron rothman


1 Answers

You have to create Session object and set max_redirects variable to 3

session = requests.Session()
session.max_redirects = 3
session.get(url)

TooManyRedirects exception will be raised if a requests exceeds maximum number of redirects.

Related github issue discussing why you can not set max_redirects per request https://github.com/kennethreitz/requests/issues/1300

like image 188
Alik Avatar answered Nov 13 '22 09:11

Alik