English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask 变量规则

URLs can be dynamically built by adding a variable part to the rule parameter. This variable part is marked as <variable-name> as a keyword argument to the function associated with the rule.

In the following example, the rule parameter of the route() decorator includes an additional part attached to the URL /hello's <name> variable part. Therefore, if you enter the URL in the browser: http://localhost:5000/hello/w3codebox, then ‘w3codebox’ will be passed as a parameter to the hello() function.

Refer to the following code -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : fr.oldtoolbag.com
# Date : 2020-08-08
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)

Save the above script to the file: hello.py and run it from the Python shell.

Next, open the browser and enter the URL => http://localhost:5000/hello/w3codebox. You will see Hello w3codebox

In addition to the default string variable part, the following converter constructor rules can be used -

NumberConverterDescription
1intAccepts integers
2floatFor floating-point values
3pathAccepts the backslash character (as a directory separator/)

All these constructor functions are used in the following code.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : fr.oldtoolbag.com
# Date : 2020-08-08
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()

Run the above code from Python Shell. Access the URL in the browser => http:// localhost:5000/blog/11.

The given numeric value is used as a parameter for the :show_blog() function. The browser displays the following output -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : fr.oldtoolbag.com
# Date : 2020-08-08
Blog Number 11

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

revision()函数将浮点数作为参数。 以下结果出现在浏览器窗口中 -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : fr.oldtoolbag.com
# Date : 2020-08-08
Revision Number 1.100000

Flask的URL规则基于Werkzeug的路由模块。 这确保了形成的URL是唯一的,并且基于Apache制定的先例。

考虑以下脚本中定义的规则 -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : fr.oldtoolbag.com
# Date : 2020-08-08
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()

两条规则看起来都很相似,但在第二条规则中,使用了尾部斜线(/)。 因此,它变成了一个规范的URL。 因此,使用/python或/python/返回相同的输出。 但是,在第一条规则的情况下, URL:/flask/会导致404 Not Found页面。