Flask变量规则

Flask变量规则 首页 / Flask入门教程 / Flask变量规则

通过将可变部分添加到规则参数中,可以动态构建URL,此变量部分标签为<variable-name>,它作为关键字参数传递给与规则关联的函数。

在以下示例中,route()装饰的rule参数包含附加到URL“/hello”的<name>变量部分, 因此,如果在浏览器中输入http://localhost:5000/hello/LearnFk,则“ LearnFk”将作为name参数提供给hello()函数。

from flask import Flask
app=Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug=True)

将上面的脚本另存为 hello.py 并从Python shell运行它。接下来,打开浏览器并输入URL http://localhost:5000/hello/LearnFk。

以下输出将显示在浏览器中。

Hello LearnFk!

除了默认的字符串变量部分,还可以使用以下转换器构造规则:

Sr.No.Converters & Remark
1

int

接受整数

2

float

对于浮点值

3

path

接受用作目录分隔符的斜杠

在下面的代码中,将使用所有这些构造函数。

from flask import Flask
app=Flask(__name__)

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()

从Python Shell运行以上代码。在浏览器中访问URL http://localhost:5000/blog/11 。

给定的数字用作 show_blog()函数的参数。浏览器显示以下输出-

Blog Number 11

在浏览器中输入此URL- http://localhost:5000/rev/1.1

无涯教程网

revision() 函数使用浮点数作为参数。以下输出出现在浏览器窗口中-

Revision Number 1.100000

Flask的URL规则基于 Werkzeug的路由模块。

from flask import Flask
app=Flask(__name__)

@app.route('/flask')
def hello_flask():
   return 'Hello Flask'

@app.route('/python/')
def hello_python():
   return 'Hello Python'

if __name__ == '__main__':
   app.run()

两条规则看起来相似,但是在第二条规则(/python/)中,使用斜杠(/)结尾成为规范的URL。因此,使用/python /python/返回相同的输出。但是在第一个规则(/flash)的情况下,/flask/ URL导致 404 Not Found 页面。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

结构思考力 · 透过结构看思考 -〔李忠秋〕

遗留系统现代化实战 -〔姚琪琳〕

深入剖析Java新特性 -〔范学雷〕

大数据经典论文解读 -〔徐文浩〕

React Hooks 核心原理与实战 -〔王沛〕

移动端自动化测试实战 -〔思寒〕

Linux实战技能100讲 -〔尹会生〕

许式伟的架构课 -〔许式伟〕

技术与商业案例解读 -〔徐飞〕

好记忆不如烂笔头。留下您的足迹吧 :)