python-requests: Limit Number of Redirects Followed

前端 未结 2 726
礼貌的吻别
礼貌的吻别 2021-01-06 03:03

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 jus

相关标签:
2条回答
  • 2021-01-06 03:21

    If you want to get the header (or other information) of the request that cause the Max Rediect Limit Exception, you can do like that:

    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 requests are the latest edition.

    0 讨论(0)
  • 2021-01-06 03:38

    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

    0 讨论(0)
提交回复
热议问题