python - 请求库 GET 方法重定向所有带有 header 位置的响应,还是仅重定向状态代码为 300 的响应?

标签 python python-requests

我知道requests库自动重定向GET具有 status code 的请求的300s 。但有时,程序员只是发送 location在标题中,但不要设置重定向的状态 ( 300s )。

所以,我想知道是否 requests使用 location 重定向所有响应在 header 中,或者如果它仅重定向状态代码为 300s 的响应?我试图在文档中找到此信息,但没有成功。

最佳答案

文档中没有明确说明这一点,但请求仅遵循重定向(自动,或者如果通过指示这样做>allow_redirects=True) - 但并非每个带有 Location header 的响应都一定是重定向。

<小时/>

Location header 有两个主要用途:

  • 重定向:带有状态代码 3xx 的响应
  • 指示新创建的资源的位置(状态代码201)。

来自 RFC 7231, Section 7.1.2 :

The "Location" header field is used in some responses to refer to a specific resource in relation to the response. The type of relationship is defined by the combination of request method and status code semantics.

[...]

For 201 (Created) responses, the Location value refers to the primary resource created by the request. For 3xx (Redirection) responses, the Location value refers to the preferred target resource for automatically redirecting the request.

因此,只有带有 Location header 状态代码 3xx 的响应才被视为重定向。 requests 模块会检查 Response.is_redirect() 中的确切条件。 :

@property
def is_redirect(self):
    """True if this Response is a well-formed HTTP redirect that could have
    been processed automatically (by :meth:`Session.resolve_redirects`).
    """
    return ('location' in self.headers and self.status_code in REDIRECT_STATI)

(由 SessionRedirectMixin.resolve_redirects() 检查)

关于python - 请求库 GET 方法重定向所有带有 header 位置的响应,还是仅重定向状态代码为 300 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515620/

相关文章:

python - 如何断言引发了 HTTP 异常?

python - 多线程Python请求

python - 使用Python登录网站并进行网络抓取

python - 升级后的Pylab

python - Django i18n 和 python 语言环境(和日期)

python - 如果 '-' 在字符串中间,则将数据帧单元格中的 'E-' 替换为 '-'

python-3.x - Cloud Natural Language API 返回 socket.gaierror : nodename nor servname provided after performing Sentiment Analysis every now and then

python - 如何连接边缘的末端以关闭它们之间的孔?

python - 异步和 rabbitmq (asynqp) : how to consume from multiple queues concurrently

python - 在 Python 3.3 中使用 requests 和 requests-oauthlib 验证 API 调用