【发布时间】:2022-01-14 22:51:57
【问题描述】:
假设我向 A 发送了一个 HTTP 请求,该请求重定向到 B,然后是 C。
response = requests.get(A_url, allow_redirects = True)
据我了解response的内容是A.
但是 response.history 中的顺序是什么?是[B,C]还是[C,B]?
【问题讨论】:
标签: python python-3.x python-requests
假设我向 A 发送了一个 HTTP 请求,该请求重定向到 B,然后是 C。
response = requests.get(A_url, allow_redirects = True)
据我了解response的内容是A.
但是 response.history 中的顺序是什么?是[B,C]还是[C,B]?
【问题讨论】:
标签: python python-3.x python-requests
从使用hist.append(resp) 的requests source code 来看,它看起来是按照看到的顺序“升序”(按顺序)排列的。所以,[A, B] 来自您的示例。
hist = [] # keep track of history
url = self.get_redirect_target(resp)
previous_fragment = urlparse(req.url).fragment
while url:
prepared_request = req.copy()
# Update history and keep track of redirects.
# resp.history must ignore the original request in this loop
hist.append(resp)
resp.history = hist[1:]
...
这是来自.resolve_redirects() 的代码块,它一直在寻找重定向,直到它不再被重定向。 . get_redirect_target(),反过来,如果没有重定向目标,则停止返回 URL(它将返回 None),结束上面看到的 while url 循环。
创建以下 Flask 应用:
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/a")
def a():
return redirect(url_for('b'))
@app.route("/b")
def b():
return redirect(url_for('c'))
@app.route("/c")
def c():
return "<p>Hello, C!</p>"
服务它:
$ python3 -m flask run
现在发送请求:
>>> import requests
>>> resp = requests.get("http://127.0.0.1:5000/a")
>>> resp.history
[<Response [302]>, <Response [302]>]
>>> [x.url for x in resp.history]
['http://127.0.0.1:5000/a', 'http://127.0.0.1:5000/b']
>>> resp.url
'http://127.0.0.1:5000/c'
【讨论】:
resp.history 将是 [A, B]。 response.url 本身就是最终目的地,C。