Flask 动态路由也叫(路由变量)
语法
<变量名>
<转换器:变量名>Code language: HTML, XML (xml)
URL 中尖括号包裹的内容为动态变量,会自动作为参数传入视图函数。
示例
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '你好 FoxDevelop'
# 1. 默认字符串变量(默认转换器:string)
@app.route('/user/<username>')
def show_user_profile(username):
return '用户 %s' % username
# 2. int整数转换器
@app.route('/post/<int:post_id>')
def show_post(post_id):
return '文章 %d' % post_id
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=False)Code language: PHP (php)
访问测试
http://127.0.0.1:5000/user/1→ 返回用户 1,username类型是字符串http://127.0.0.1:5000/post/1→ 返回文章 1,post_id类型是整数
访问
/post/abc会匹配失败,页面404,因为int转换器只接受数字。
对照表
| 转换器 | 作用 |
|---|---|
string(默认) | 匹配不包含 / 的文本,不写转换器默认就是它 |
int | 只匹配正整数,参数自动转为int类型 |
float | 匹配正浮点数 |
path | 和string类似,允许包含斜杠 / |
例子
# float示例
@app.route('/price/<float:money>')
def get_price(money):
return f"价格:{money}"
# path示例(可以传递带/的路径)
@app.route('/file/<path:filepath>')
def read_file(filepath):
return f"文件路径:{filepath}"Code language: PHP (php)
访问 http://127.0.0.1:5000/file/doc/read.txt,filepath 得到 doc/read.txt
注意
- 变量名称必须一致
路由<username>和函数参数username名字要一模一样。 - 转换器会做类型强制校验,不符合格式直接404。
- 默认
string不能识别/,如果URL里需要斜杠,使用path转换器。