Python requests: limiting the number of redirects
Is there a way to limit the number of redirects that will be performed on python requests when doing a GET?
I know about allow_redirects=False
, but that just prevents the redirection all together. I'm looking for a way to keep track of the redirect, up to some maximum number of conversions.
# 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
Thank!
source to share
You need to create an object Session
and set the variable max_redirects
to 3
session = requests.Session() session.max_redirects = 3 session.get(url)
TooManyRedirects
the exception will be raised if requests exceed the maximum number of redirects.
Related github issue discussing why you can't install max_redirects
per request https://github.com/kennethreitz/requests/issues/1300
source to share
If you want to get the header (or other information) of the request that caused the Max Rediect Limit Exception, you can do this:
session = requests.Session()
session.max_redirects = 1
try:
r = session.post(url, headers = headers, params = querystring, data = payload)
except requests.exceptions.TooManyRedirects as exc:
r = exc.response
Make sure your details are the latest release.
source to share