我知道requests
库自动重定向GET
具有 status code
的请求的300s
。但有时,程序员只是发送 location
在标题中,但不要设置重定向的状态 ( 300s
)。
所以,我想知道是否 requests
使用 location
重定向所有响应在 header 中,或者如果它仅重定向状态代码为 300s
的响应?我试图在文档中找到此信息,但没有成功。
最佳答案
文档中没有明确说明这一点,但请求
仅遵循重定向(自动,或者如果通过指示这样做>allow_redirects=True
) - 但并非每个带有 Location
header 的响应都一定是重定向。
Location
header 有两个主要用途:
- 重定向:带有状态代码
3xx
的响应 - 指示新创建的资源的位置(状态代码
201
)。
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)
关于python - 请求库 GET 方法重定向所有带有 header 位置的响应,还是仅重定向状态代码为 300 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515620/