显示回复位置header,包括是否有问号

Show response location header, including if there is a question mark

对于 Python 请求,如何确定从服务器返回的位置 header 的值?如果我有简单的网络服务器

from flask import Flask, Response, request

def root():
    return Response(headers={
        'location': 'http://some.domain.com/?'  # Note the ?
    })

app = Flask('app')
app.add_url_rule('/', view_func=root)

app.run(host='0.0.0.0', port=8081, debug=False)

和运行

import requests

response = requests.get('http://localhost:8081/', allow_redirects=False)
print(response.headers['location'])

明白了

http://some.domain.com/

没有/

后面的问号

这与 有关。我正在使用 Python 请求来测试返回重定向的应用程序,但我意识到请求正在从位置 header.

中删除尾随问号

这是一个 red-herring:请求没有从位置 header 中删除问号。如果Flask服务器改为return what-should-be两个相同的header,一个location和一个test

def root():
    return Response(headers={
        'location': 'http://some.domain.com/?',  # Note the ?
        'test':     'http://some.domain.com/?',  # Note the ?
    })

然后我们通过套接字发出原始 HTTP 请求

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
sock.connect(('127.0.0.1', 8081))  

request = \
    f'GET / HTTP/1.1\r\n' \
    f'host:127.0.0.1\r\n' \
    f'\r\n'
sock.send(request.encode()) 
response = b''
while b'\r\n\r\n' not in response:
    response += sock.recv(4096)
sock.close()
print(response)

响应包含 test header 和 ?

test: http://some.domain.com/?\r\n

但是 location header 没有 ?

Location: http://some.domain.com/\r\n

所以 Flask(或服务器中使用的其他组件之一)似乎在操纵位置 header returned.