Flask路由的参数传递

一、在Flask框架中,路由是指将URL映射到相应的处理函数。在Flask中,可以使用装饰器来定义路由。

二、要传递参数给路由处理函数,可以使用Flask中的变量规则。可以在路由定义中使用尖括号 <variable> 来定义变量规则,然后在处理函数中通过 request.view_args 获取传递的参数。

例:

from flask import Flask, request

app = Flask(__name__)

@app.route('/user/<username>')
def user_profile(username):
    return 'Hello, ' + username + '!'

@app.route('/post/<int:post_id>')
def post_detail(post_id):
    return 'You requested post with ID ' + str(post_id)

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

在上面的示例中,我们定义了两个路由:
/user/<username>/post/<int:post_id>

/user/<username> 路由中,我们使用 <username> 定义了一个变量规则,它会匹配 URL 中的任意文本,并将其作为参数传递给 user_profile() 处理函数。在 /post/<int:post_id> 路由中,我们使用 <int:post_id> 定义了一个变量规则,它会匹配 URL 中的任意整数,并将其作为参数传递给 post_detail() 处理函数。

在处理函数中,我们可以通过 request.view_args 来获取传递的参数。例如,在 user_profile() 函数中,我们可以使用 request.view_args['username'] 来获取传递的 username 参数。在 post_detail() 函数中,我们可以使用 request.view_args['post_id'] 来获取传递的 post_id 参数。