Flask URL构建

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)

上述脚本有一个函数 hello_user(name),它接受来自 URL 的参数的值。

hello_user() 函数检查接收的参数是否与 ‘admin’ 匹配。如果匹配,则使用 url_for() 将应用程序重定向到 hello_admin() 函数,否则重定向到将接收的参数作为 guest 参数传递给它的 hello_guest() 函数。

保存上面的代码并从 Python shell 运行。

打开浏览器并输入URL http://localhost:5000/user/admin

浏览器中的应用程序响应是: Hello Admin

在浏览器中输入以下URL http://localhost:5000/user/mvl

应用程序响应现在更改为:Hello mvl as Guest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值