路由
现代 web 应用都使用有意义的 URL ,这样有助于用户记忆,网页会更得到用户的青睐, 提高回头率。
使用 route()
装饰器来把函数绑定到 URL:
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
但是能做的不仅仅是这些!你可以动态变化 URL 的某些部分, 还可以为一个函数指定多个规则。
在这里,URL ‘/ hello’ 规则绑定到hello_world()函数。 因此,如果用户访问http:// localhost:5000 / hello URL,hello_world()函数的输出将在浏览器中呈现。
application对象的add_url_rule()函数也可用于将URL与函数绑定,如上例所示,使用route()。
装饰器的目的也由以下表示:
def hello_world():
return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)
变量规则
通过把 URL 的一部分标记为 <variable_name>
就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 <converter:variable_name>
,可以 选择性的加上一个转换器,为变量指定规则。请看下面的例子:
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % escape(subpath)
转换器类型:
string |
(缺省值) 接受任何不包含斜杠的文本 |
---|---|
int |
接受正整数 |
float |
接受正浮点数 |
path |
类似 string ,但可以包含斜杠 |
uuid |
接受 UUID 字符串 |
Flask URL构建(url_for)
url_for()函数对于动态构建特定函数的URL非常有用。该函数接受函数的名称作为第一个参数,以及一个或多个关键字参数,每个参数对应于URL的变量部分。
为什么不在把 URL 写死在模板中,而要使用反转函数 url_for()
动态构建?
- 反转通常比硬编码 URL 的描述性更好。
- 你可以只在一个地方改变 URL ,而不用到处乱找。
- URL 创建会为你处理特殊字符的转义和 Unicode 数据,比较直观。
- 生产的路径总是绝对路径,可以避免相对路径产生副作用。
- 如果你的应用是放在 URL 根路径之外的地方(如在
/myapplication
中,不在/
中),url_for()
会为你妥善处理。
以下脚本演示了如何使用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()函数,否则重定向到将接收的参数作为guest参数传递给它的hello_guest()函数。
保存上面的代码并从Python shell运行。
打开浏览器并输入URL - http://localhost:5000/user/admin
浏览器中的应用程序响应是:
Hello Admin
在浏览器中输入以下URL - http://localhost:5000/user/mvl
应用程序响应现在更改为:
Hello mvl as Guest