我想检测请求来自 localhost:5000
或者 foo.herokuapp.com
主机的哪个路径被请求了。如何获取有关 Flask 请求的此信息?
假设您的应用程序正在侦听以下应用程序根目录:
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
另一个例子:
请求:
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
request.full_path
的人们改用request.environ['RAW_URI']
。这是因为当实际查询路径为/alert/dingding/test
时,request.full_path
返回/alert/dingding/test?
,结果会添加一个多余的问号,这可能是不希望的。 - AnnieFromTaiwan你应该尝试:
request.url
它应该始终工作,即使在本地主机上(我刚刚这样做了)。
如果你正在使用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')
http://www.example.com/myapplication/foo/page.html?x=y
用户需要 y
您可以使用
request.args.get("x")
http://www.example.com/
而不是http://www.example.com/myapplication/
base_url 返回的是http://www.example.com/myapplication/
- moto