url_for()函数对于动态构建特定函数的URL非常有用,该函数接受函数名称作为第一个参数,以及一个或多个关键字参数,每个参数对应于URL的可变部分。
以下脚本演示了 url_for()函数的用法。
from flask import Flask, redirect, url_for app=Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest=name)) if __name__ == '__main__': app.run(debug=True)
上面的脚本具有 user(name)函数,该函数从URL接受其参数的值。
User()函数检查收到的参数是否与'admin'相匹配。如果匹配,则使用 url_for()将应用程序重定向到 hello_admin()函数,否则将传递接收到的 hello_guest()函数。
保存上面的代码,然后从Python shell运行。
打开浏览器,然后以- http://localhost:5000/user/admin 输入URL
Hello Admin
在浏览器中输入以下URL- http://localhost:5000/user/mvl
应用程序响应现在更改为-
Hello mvl as Guest