python-requests:限制遵循的重定向数量
python-requests: Limit Number of Redirects Followed
有没有办法限制 python 请求在执行 GET 时将遵循的重定向次数?
I know about allow_redirects=False
,但这只会一起阻止重定向。我正在寻找一种方法来跟踪重定向,最多达到某个最大跃点数。
# 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
谢谢!
您必须创建 Session
对象并将 max_redirects
变量设置为 3
session = requests.Session()
session.max_redirects = 3
session.get(url)
TooManyRedirects
如果请求超过重定向的最大数量,将引发异常。
相关 github 问题讨论了为什么您不能为每个请求设置 max_redirects
https://github.com/kennethreitz/requests/issues/1300
如果你想获取导致Max Rediect Limit Exception的请求的header(或其他信息),你可以这样做:
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
确保您的请求是最新版本。
有没有办法限制 python 请求在执行 GET 时将遵循的重定向次数?
I know about allow_redirects=False
,但这只会一起阻止重定向。我正在寻找一种方法来跟踪重定向,最多达到某个最大跃点数。
# 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
谢谢!
您必须创建 Session
对象并将 max_redirects
变量设置为 3
session = requests.Session()
session.max_redirects = 3
session.get(url)
TooManyRedirects
如果请求超过重定向的最大数量,将引发异常。
相关 github 问题讨论了为什么您不能为每个请求设置 max_redirects
https://github.com/kennethreitz/requests/issues/1300
如果你想获取导致Max Rediect Limit Exception的请求的header(或其他信息),你可以这样做:
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
确保您的请求是最新版本。