变量规则
您可以通过使用标记部分将可变部分添加到URL <variable_name>。然后,您的函数将接收<variable_name> 作为关键字参数。或者,您可以使用转换器指定参数的类型<converter:variable_name>。
@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
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % subpath
转换器类型:
string | (默认值)接受任何没有斜杠的文本 |
int | 接受正整数 |
float | 接受正浮点值 |
path | 喜欢string但也接受斜线 |
uuid | 接受UUID字符串 |
唯一的URL /重定向行为
以下两个规则在使用尾部斜杠时有所不同。
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
projects端点的规范URL 具有尾部斜杠。它类似于文件系统中的文件夹。如果您访问的URL没有斜杠,则Flask会将您重定向到带有斜杠的规范URL。
about端点的规范URL 没有尾部斜杠。它类似于文件的路径名。使用尾部斜杠访问URL会产生404“未找到”错误。这有助于保持这些资源的URL唯一,这有助于搜索引擎避免两次索引相同的页面。