Python 如何获取 Flask 请求 url 的不同部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15974730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the different parts of a Flask request's url?
提问by Dogukan Tufekci
I want to detect if the request came from the localhost:5000or foo.herokuapp.comhost and what path was requested. How do I get this information about a Flask request?
我想检测请求是否来自localhost:5000或foo.herokuapp.com主机以及请求的路径。如何获取有关 Flask 请求的信息?
采纳答案by icecrime
You can examine the url through several Requestfields:
您可以通过几个Request字段检查网址:
A user requests the following URL:
http://www.example.com/myapplication/page.html?x=yIn 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/
用户请求以下 URL:
http://www.example.com/myapplication/page.html?x=y在这种情况下,上述属性的值如下:
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.
您可以使用适当的分割轻松提取主体部分。
回答by Ran
you should try:
你应该试试:
request.url
It suppose to work always, even on localhost (just did it).
它假设始终有效,即使在本地主机上也是如此(刚刚做到了)。
回答by chason
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
回答by Antonio
If you are using Python, I would suggest by exploring the request object:
如果您使用的是 Python,我建议您探索 request 对象:
dir(request)
dir(request)
Since the object support the method dict:
由于对象支持方法dict:
request.__dict__
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
它可以打印或保存。我用它在 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')

