关于python:如何获取Flask请求网址的不同部分?

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

我想检测请求是否来自localhost:5000foo.herokuapp.com主机以及请求的路径。 如何获得有关Flask请求的信息?


您可以通过几个Request字段检查url:

A user requests the following URL:

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

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

1
2
3
4
5
    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/

您可以通过适当的拆分轻松提取主体部分。


另一个例子:

请求:

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

然后:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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


你应该试试:

1
request.url

它假设即使在localhost上也可以一直工作(只是这样做了)。