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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

You can examine the url through several Request fields:

A user requests the following URL:

    http://www.example.com/myapplication/page.html?x=y

In this case the values of the above mentioned attributes would be the following:

    path             /page.html
    script_root      /myapplication
    base_url         http://www.example.com/myapplication/page.html
    url              http://www.example.com/myapplication/page.html?x=y
    url_root         http://www.example.com/myapplication/

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

Questions:
Answers:

you should try:

request.url 

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

Questions:
Answers:

another example:

request: http://127.0.0.1:5000/alert/dingding/test

then:

request.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.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.path:                /alert/dingding/test