How do I get the different parts of a Flask request's url?

PythonUrlFlask

Python Problem Overview


I want to detect if the request came from the localhost:5000 or foo.herokuapp.com host and what path was requested. How do I get this information about a Flask request?

Python Solutions


Solution 1 - Python

You can examine the url through several Request fields:

> Imagine your application is listening on the following application root: > > http://www.example.com/myapplication > > And a user requests the following URI: > > http://www.example.com/myapplication/foo/page.html?x=y > > In this case the values of the above mentioned attributes would be the following: > > path /foo/page.html > full_path /foo/page.html?x=y > script_root /myapplication > base_url http://www.example.com/myapplication/foo/page.html > url http://www.example.com/myapplication/foo/page.html?x=y > url_root http://www.example.com/myapplication/

You can easily extract the host part with the appropriate splits.

Solution 2 - Python

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

Solution 3 - Python

you should try:

request.url 

It suppose to work always, even on localhost (just did it).

Solution 4 - Python

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDogukan TufekciView Question on Stackoverflow
Solution 1 - PythonicecrimeView Answer on Stackoverflow
Solution 2 - PythonchasonView Answer on Stackoverflow
Solution 3 - PythonRanView Answer on Stackoverflow
Solution 4 - PythonAntonioView Answer on Stackoverflow