如何获取Flask请求URL的不同部分?

235

我想检测请求来自 localhost:5000 或者 foo.herokuapp.com 主机的哪个路径被请求了。如何获取有关 Flask 请求的此信息?

5个回答

365
您可以通过几个请求字段来检查URL:

假设您的应用程序正在侦听以下应用程序根目录:

http://www.example.com/myapplication

而用户请求以下URI:

http://www.example.com/myapplication/foo/page.html?x=y
在这种情况下,上述属性的值将如下所示:
    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/
您可以通过适当的分割方式轻松提取主机部分。以下是使用示例:
from flask import request

@app.route('/')
def index():
    return request.base_url

4
刚接触Flask,我不知道请求对象从哪里来以及它是如何工作的,这里是链接:http://flask.pocoo.org/docs/0.12/reqcontext/ - Ulysse BN
1
url_root 返回的是 http://www.example.com/ 而不是 http://www.example.com/myapplication/base_url 返回的是 http://www.example.com/myapplication/ - moto
我的应用程序路由类似于 @app.route('/index/int:id1/int:id2'),如何从请求中获取不带变量的路径。我期望结果为 /index。应该使用哪个 Flask 函数? - user4772933

338

另一个例子:

请求:

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

那么:

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

18
由于它提供了更多详细信息,这个答案应该被接受。 - pfabri
3
这是一个很棒的回答。非常实用和全面。 - Tao Starbow
2
建议希望使用request.full_path的人们改用request.environ['RAW_URI']。这是因为当实际查询路径为/alert/dingding/test时,request.full_path返回/alert/dingding/test?,结果会添加一个多余的问号,这可能是不希望的。 - AnnieFromTaiwan
请求.远程地址 对应 127.0.0.1 - PYK
2
Flask中的“host_url”、“root_url”和“url_root”有什么不同? - CS QGB
request.query_string - anvd

14

你应该尝试:

request.url 

它应该始终工作,即使在本地主机上(我刚刚这样做了)。


Flask中的“host_url”、“root_url”和“url_root”有什么不同? - CS QGB

2

如果你正在使用Python,我建议探索请求对象:

dir(request)

由于该对象支持方法dict

request.__dict__

可以打印或保存。我在Flask中使用它来记录404代码:

@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')

Flask中的“host_url”、“root_url”和“url_root”有什么不同? - CS QGB

1
如果用户请求以下URI:
http://www.example.com/myapplication/foo/page.html?x=y

用户需要 y

您可以使用

request.args.get("x")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接