Python Flask:路由

来自CloudWiki
Cloud17讨论 | 贡献2022年1月12日 (三) 08:37的版本 (创建页面,内容为“==定义== 处理URL和函数之间关系的程序 称为路由, 而这个函数称为视图函数。 ==Flask中使用路由== 使用程序实例提供的app.rou…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

定义

处理URL和函数之间关系的程序 称为路由,

而这个函数称为视图函数。

Flask中使用路由

使用程序实例提供的app.route装饰器,

把装饰的函数注册为路由:

from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return '你好'

if __name__ == '__main__':
    #app.debug = True
    app.run()

当浏览器访问 http://127.0.0.1:5000/hello 时,URL会触发hello_world()函数,执行函数体中的代码。

给URL添加变量

from flask import Flask
app = Flask(__name__)

@app.route('/user/<username>')
def show_user_profile(username):
    return 'User: %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post ID: %d' % post_id

if __name__ == '__main__':
    #app.debug = True
    app.run()


访问http://127.0.0.1:5000/user/张三 时就会触发show_use_profile函数

访问http://127.0.0.1:5000/post/123 时就会触发show_post函数

show_post()函数使用了转换器,它有下面几种类型:

  • Int
  • float
  • path

代码中使用int:post_id将其设置为整形