要给 URL 添加变量部分,你可以把这些特殊的字段标记为 <variable_name>
, 这个部分将会作为命名参数传递到你的函数。规则可以用 <converter:variable_name>
指定一个可选的转换器。这里有一些不错的例子:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Index Page"
@app.route('/hello')
def hello_world():
return "Hello world!"
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % 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
if __name__ == '__main__':
app.run()
转换器有下面几种:
int | 接受整数 |
---|---|
float | 同 int ,但是接受浮点数 |
path | 和默认的相似,但也接受斜线 |
【唯一 URL / 重定向行为】
Flask 的 URL 规则基于 Werkzeug 的路由模块。这个模块背后的思想是基 于 Apache 以及更早的 HTTP 服务器主张的先例,保证优雅且唯一的 URL。
以这两个规则为例:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
虽然它们看起来着实相似,但它们结尾斜线的使用在 URL 定义 中不同
- 第一种情况中,指向 projects 的规范 URL 尾端有一个斜线,访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去。
- 第二种情况的 URL 结尾不带斜线,访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误
这个行为使得在遗忘尾斜线时,允许关联的 URL 接任工作,与 Apache 和其它的服务器的行为并无二异。此外,也保证了 URL 的唯一,有助于避免搜索引擎索引同一个页面两次。