路由变量

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)

访问测试

  1. http://127.0.0.1:5000/user/1 → 返回 用户 1username 类型是字符串
  2. http://127.0.0.1:5000/post/1 → 返回 文章 1post_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.txtfilepath 得到 doc/read.txt

注意

  1. 变量名称必须一致
    路由 <username> 和函数参数 username 名字要一模一样。
  2. 转换器会做类型强制校验,不符合格式直接404。
  3. 默认 string 不能识别 /,如果URL里需要斜杠,使用 path 转换器。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注