请稍候,加载中....

路由概念

现代web程序更倾向于为用户提供有意义的url地址来访问站点,因为对于用户来说,意义明确且易于记忆的地址,可以方便他们重新访问站点

flask通过route装饰器来将一个函数绑定到某个url上

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'

您可以做更多!您可以使部分URL动态化,并将多个url匹配规则附加到一个函数上。

变量规则

您可以通过使用标记部分来将可变部分添加到URL <variable_name>。然后,您的函数将接收<variable_name> 作为关键字参数。

作为一项可选措施,您可以使用转换器指定类似的参数类型<converter:variable_name>

变量规则示例

from markupsafe import escape

# show_user_profile函数将可以接受在/user/<username>传递的username部分
# 举例: http://xxxx/user/luxp, 相当于给show_user_profile传入了实参
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)

int示例:这里<int:post_id>,表示将post_id转换为int后再传入给show_post

@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

path示例:将subpath转换为path

@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字符串

唯一URL /重定向行为

以下两个规则在使用斜杠时有所不同

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'

当访问/projects时,flask会自动帮用户定向到/projects/

当访问/about时,如果在浏览器地址中给/about添加了/,变成/about/访问时,会显示404错误

这有助于使这些资源的URL保持唯一,从而有助于搜索引擎避免对同一页面进行两次索引(seo优化)

 


Python学习手册-