Flask 简明教程

Flask – URL Building

url_for() 函数对于为特定函数动态构建 URL 非常有用。此函数接收函数名称作为第一个参数,并接收一个或多个关键字参数,每个都对应着 URL 的变量部分。

The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL.

以下脚本展示了 url_for() 函数的用法。

The following script demonstrates use of url_for() function.

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 中传递给它的参数的值。

The above script has a function user(name) which accepts a value to its argument from the URL.

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

The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.

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

Save the above code and run from Python shell.

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

Open the browser and enter URL as − http://localhost:5000/user/admin

浏览器中的应用程序响应为 −

The application response in browser is −

Hello Admin

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

Enter the following URL in the browser − http://localhost:5000/user/mvl

应用程序响应现在更改为 −

The application response now changes to −

Hello mvl as Guest