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

Requests library GET method redirects all responses with a location in the header or only responses with status code of 300s?

我知道 requests 库会自动重定向 GET 具有 status code300s 请求。但有时,程序员只是在 header 中发送 location,而没有设置重定向状态 (300s)。

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

这在文档中没有明确说明,但 requests 仅遵循 redirects(自动,或者如果指示通过 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() 检查)