我想检测请求是否来自localhost:5000或foo.herokuapp.com主机以及请求的路径。如何获得关于Flask请求的信息?
当前回答
你可以通过以下几个Request字段来检查url:
Imagine your application is listening on the following application root: http://www.example.com/myapplication And a user requests the following URI: http://www.example.com/myapplication/foo/page.html?x=y In this case the values of the above mentioned attributes would be the following: 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
其他回答
你应该试试:
request.url
它应该总是工作,甚至在localhost(刚刚做了)。
如果你正在使用Python,我建议通过探索请求对象:
dir(请求)
因为对象支持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')
你可以通过以下几个Request字段来检查url:
Imagine your application is listening on the following application root: http://www.example.com/myapplication And a user requests the following URI: http://www.example.com/myapplication/foo/page.html?x=y In this case the values of the above mentioned attributes would be the following: 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
推荐文章
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- URL中的“#:~:text=”位置哈希值到底是什么?
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc