Flask request: determine exact path, including if

2020-04-16 05:32发布

问题:

Is there a way to determine what the path was requested to the server, including if it included a question mark? The application

from flask import Flask, Response, request

def root():
    return Response(
        f'full_path:{request.full_path} '
        f'path:{request.path} '
        f'query_string:{request.query_string} '
        f'url:{request.url}'
    )

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

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

always results in

full_path:/? path:/ query_string:b'' url:http://localhost:8081/

if requesting either

http://localhost:8081/?

or

http://localhost:8081/

This may seem unimportant in a lot of cases, but I'm making an authentication flow with multiple redirections, where the user is meant to end up at the exact same URL as they started. At the moment, I can't see a way to ensure this happens with Flask.

回答1:

In addition to the fields you have already mentioned, Values in 'environ' field might be useful in your case:

def root():
    return Response(
        f'raw_uri:{request.environ["RAW_URI"]} '
        f'request_uri:{request.environ["REQUEST_URI"]}'
    )

Input:

http://localhost:8081/?

Output:

raw_uri:/?
request_uri:/?

Input:

http://localhost:8081/

Output:

raw_uri:/
request_uri:/