如何获取 Flask 请求的 URL 的不同部分?
- 2025-03-04 08:25:00
- admin 原创
- 70
问题描述:
我想检测请求是否来自localhost:5000
或foo.herokuapp.com
主机以及请求的路径。如何获取有关 Flask 请求的这些信息?
解决方案 1:
您可以通过几个字段检查 URL Request
:
假设您的应用程序正在监听以下应用程序根:
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
解决方案 2:
另一个例子:
要求:
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
解决方案 3:
你应该尝试:
request.url
它应该一直工作,即使在本地主机上(刚刚这样做了)。
解决方案 4:
如果您使用 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__}
')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
解决方案 5:
如果用户请求以下 URI:
http://www.example.com/myapplication/foo/page.html?x=y
并且用户想要
你可以使用
request.args.get("x")
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD