Ad

Show Response Location Header, Including If There Is A Question Mark

With Python requests, how can I determine the value of the location header returned from the server? If I have the simple webserver

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)

and run

import requests

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

I see

http://some.domain.com/

without the question mark after the /


This is related to Flask request: determine exact path, including if there is a question mark . I was using Python requests to test an application that returned redirects, but I realised that requests was removing trailing question marks from the location header.

Ad

Answer

This was a red-herring: requests isn't stripping the question mark from the location header. If the Flask server is changed to return what-should-be two identical headers, one location and one test

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

and we make a raw HTTP request via a socket

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)

the response contains a test header with the ?

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

but a location header without the ?

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

So it's Flask (or one of the other components used in the server) that seems to be manipulating the location header returned.

Ad
source: stackoverflow.com
Ad