flask 入门学习(二)

路由

接下来给第一章的小例子增加一点东西:

@app.route('/apple')
def apple():
    return 'This is appple'

@app.route('/orange/')
def orange():
    return 'This is orange'
  • 这样的形式,可以通过在浏览器 127.0.0.1/apple 打开,

唯一的URL 重定向行为

让我们再看一下上面的两个路由,两个不同之处在于是否使用尾部的斜杠。

  • orange 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件夹。 访问一个没有斜杠结尾的 URL 时 Flask 会自动进行重定向,帮你在尾部加上一个斜杠。(说人话就是,可以127.0.0.1/orange/ 访问,也可以127.0.0.1/orange 访问)
  • apple 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这个 URL 时添加了尾部斜杠就会得到一个 404 错误。这样可以保持 URL 唯一,并帮助 搜索引擎避免重复索引同一页面(说人话就是只能127.0.0.1/apple 访问)
    合理的利用这个唯一性去选择路由,如果没有特殊的需求,建议使用 /orange/ 形式

变量规则

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

import re
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % re.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' % re.escape(subpath)
  • 这里转换器类型有 string、int、float、path(类似string,可以包含斜杠)、uuid
原文地址:https://www.cnblogs.com/longbigbeard/p/14142488.html