要给 URL 添加变量部分,你可以把这些特殊的字段标记为 <variable_name> , 这个部分将会作为命名参数传递到你的函数。规则可以用 <converter:variable_name> 指定一个可选的转换器。这里有一些不错的例子:

    1. from flask import Flask
    2. app = Flask(__name__)
    3. @app.route('/')
    4. def index():
    5. return "Index Page"
    6. @app.route('/hello')
    7. def hello_world():
    8. return "Hello world!"
    9. @app.route('/user/<username>')
    10. def show_user_profile(username):
    11. # show the user profile for that user
    12. return 'User %s' % username
    13. @app.route('/post/<int:post_id>')
    14. def show_post(post_id):
    15. # show the post with the given id, the id is an integer
    16. return 'Post %d' % post_id
    17. if __name__ == '__main__':
    18. app.run()

    image.png
    转换器有下面几种:

    int 接受整数
    float 同 int ,但是接受浮点数
    path 和默认的相似,但也接受斜线

    【唯一 URL / 重定向行为】
    Flask 的 URL 规则基于 Werkzeug 的路由模块。这个模块背后的思想是基 于 Apache 以及更早的 HTTP 服务器主张的先例,保证优雅且唯一的 URL。
    以这两个规则为例:

    1. @app.route('/projects/')
    2. def projects():
    3. return 'The project page'
    4. @app.route('/about')
    5. def about():
    6. return 'The about page'

    虽然它们看起来着实相似,但它们结尾斜线的使用在 URL 定义 中不同

    • 第一种情况中,指向 projects 的规范 URL 尾端有一个斜线,访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去。
    • 第二种情况的 URL 结尾不带斜线,访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误

    image.png
    这个行为使得在遗忘尾斜线时,允许关联的 URL 接任工作,与 Apache 和其它的服务器的行为并无二异。此外,也保证了 URL 的唯一,有助于避免搜索引擎索引同一个页面两次。