路由

现代 web 应用都使用有意义的 URL ,这样有助于用户记忆,网页会更得到用户的青睐, 提高回头率。

使用 route()装饰器来把函数绑定到 URL:

  1. @app.route('/')
  2. def index():
  3. return 'Index Page'
  4. @app.route('/hello')
  5. def hello():
  6. return 'Hello, World'

但是能做的不仅仅是这些!你可以动态变化 URL 的某些部分, 还可以为一个函数指定多个规则。

在这里,URL ‘/ hello’ 规则绑定到hello_world()函数。 因此,如果用户访问http:// localhost:5000 / hello URL,hello_world()函数的输出将在浏览器中呈现。

application对象的add_url_rule()函数也可用于将URL与函数绑定,如上例所示,使用route()

装饰器的目的也由以下表示:

  1. def hello_world():
  2. return hello world
  3. app.add_url_rule(‘/’, hello’, hello_world)

变量规则

通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 <converter:variable_name> ,可以 选择性的加上一个转换器,为变量指定规则。请看下面的例子:

  1. @app.route('/user/<username>')
  2. def show_user_profile(username):
  3. # show the user profile for that user
  4. return 'User %s' % escape(username)
  5. @app.route('/post/<int:post_id>')
  6. def show_post(post_id):
  7. # show the post with the given id, the id is an integer
  8. return 'Post %d' % post_id
  9. @app.route('/path/<path:subpath>')
  10. def show_subpath(subpath):
  11. # show the subpath after /path/
  12. return 'Subpath %s' % escape(subpath)

转换器类型:

string (缺省值) 接受任何不包含斜杠的文本
int 接受正整数
float 接受正浮点数
path 类似 string ,但可以包含斜杠
uuid 接受 UUID 字符串

Flask URL构建(url_for)

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

为什么不在把 URL 写死在模板中,而要使用反转函数 url_for() 动态构建?

  1. 反转通常比硬编码 URL 的描述性更好。
  2. 你可以只在一个地方改变 URL ,而不用到处乱找。
  3. URL 创建会为你处理特殊字符的转义和 Unicode 数据,比较直观。
  4. 生产的路径总是绝对路径,可以避免相对路径产生副作用。
  5. 如果你的应用是放在 URL 根路径之外的地方(如在 /myapplication 中,不在 / 中), url_for() 会为你妥善处理。

以下脚本演示了如何使用url_for()函数:

  1. from flask import Flask, redirect, url_for
  2. app = Flask(__name__)
  3. @app.route('/admin')
  4. def hello_admin():
  5. return 'Hello Admin'
  6. @app.route('/guest/<guest>')
  7. def hello_guest(guest):
  8. return 'Hello %s as Guest' % guest
  9. @app.route('/user/<name>')
  10. def hello_user(name):
  11. if name =='admin':
  12. return redirect(url_for('hello_admin'))
  13. else:
  14. return redirect(url_for('hello_guest',guest = name))
  15. if __name__ == '__main__':
  16. app.run(debug = True)

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

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

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

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

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

  1. Hello Admin

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

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

  1. Hello mvl as Guest