Flask教程:路由实现

概述

路由,就是将 URL 和 函数 绑定。

此时函数称之为 视图函数,即:view_func

当访问这个 URL 时,Flask框架就将这个请求交给这个 函数 处理

实现方式1:装饰器

通过 装饰器@app.route('') 实现将 URL 和 函数 进行绑定

如下:

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

解释:

在上面的代码中 @app.route('/') 表示将 URL根路径 和 index() 函数 进行绑定

注意

路由中的 url 必须从 / 开始,如果写成 @app.route('') ,会报下面错误:

ValueError: urls must start with a leading slash

实现方式2:add_url_rule()

调用Flask类的

add_url_rule(rule, endpoint=None, view_func=None, **options)

方法实现,如下代码:

def index():
    return 'Hello, World!'

app.add_url_rule('/',view_func=index)

解释:

将 URL根路径 和 index() 函数 进行绑定

装饰器路由的理解

装饰器 @app.route('') 是调用Flask类的

add_url_rule(rule, endpoint=None, view_func=None, **options)

方法实现的

同一 URL 绑定 多个视图函数

同一 URL 绑定 多个视图函数,在匹配过程中,至上而下匹配第一个视图函数

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

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

浏览器访问网址:http://127.0.0.0:5000/hello 显示的是 hello ,即 hello() 函数的结果

多个URL 绑定一个视图函数

@app.route('/login')
@app.route('/doLogin')
def login():
    return '登录'

浏览器访问网址:http://127.0.0.0:5000/login 和 http://127.0.0.0:5000/doLogin ,都能执行 login() 函数,即:显示的结果是一样的


原文出处:/show_1EF3UE3DjIQD.html