主要摘引自Flask文档的《快速入门》章节

let name: String = "wtf!"

启用调试模式

app.run(debug=True)

多个地址Route的写法

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

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

附加变量

  • 附加原始变量:<variable_name>
@app.route('/user/<username>')
def show_user_profile(username):
    # 展示用户名
    return 'User {304f6ed0b3d59a494ff3bafd10e3c2eb0fd01a1c7bd37925658f43c0521dfc40}s' {304f6ed0b3d59a494ff3bafd10e3c2eb0fd01a1c7bd37925658f43c0521dfc40} username
  • 附加转换变量:<converter:variable_name>
@app.route('/post/<int:post_id>')
def show_post(post_id):
    # 展示int类型的post_id
    return 'Post {304f6ed0b3d59a494ff3bafd10e3c2eb0fd01a1c7bd37925658f43c0521dfc40}d' {304f6ed0b3d59a494ff3bafd10e3c2eb0fd01a1c7bd37925658f43c0521dfc40} post_id

网址的唯一性

根据URL地址结尾是否带有/,可以分为以下两种情况:

  • 结尾带有/
@app.route('/projects/')
def projects():
    return 'The project page'

在这种情况下,无论输入xxx/projects/还是xxx/projects,都能够正确访问到projects页面,而不用担心404错误

  • 结尾不带/
@app.route('/about')
def about():
    return 'The about page"

在这种情况下,访问xxx/about没有问题,而访问xxx/about/就会报404

构建URL

使用url_for()函数来构造URL:

函数格式:url_for('函数名', 参数)

@app.route('/profile')
def profile(username): 
    pass
    
print url_for('profile', username='John Doe')
# 输出/user/John{304f6ed0b3d59a494ff3bafd10e3c2eb0fd01a1c7bd37925658f43c0521dfc40}20Doe

动态构建URL的好处:

  1. 比硬编码更具备描述性
  2. 允许你一次性修改 URL,而不是到处去找 URL 做修改。
  3. URL 构建会显式地处理特殊字符和 Unicode 数据的转义
  4. 如果应用不位于 URL 的根路径,urlfor() 会为你妥善地处理这些。