Flask 学习-20. route 路由中的 endpoint 参数

前言

@app.route 中的 endpoint 参数,就相当于django中的name参数,用来反向生成URL。

url_for() 函数

url_for() 函数用于构建指定函数的 URL。它把函数名称作为第一个参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。

为什么不在把 URL 写死在模板中,而要使用反转函数 url_for() 动态构建?

  • 反转通常比硬编码 URL 的描述性更好。
  • 你可以只在一个地方改变 URL ,而不用到处乱找。
  • URL 创建会为你处理特殊字符的转义和 Unicode 数据,比较直观。
  • 生产的路径总是绝对路径,可以避免相对路径产生副作用。
  • 如果你的应用是放在 URL 根路径之外的地方(如在 /myapplication 中,不在 / 中), url_for() 会为你妥善处理。

例如,这里用url_for() 函数通过视图函数名称,反向获取到访问的url地址

from flask import url_for, Flask


app = Flask(__name__)


@app.route('/api/v1/hello')
def hello_view():
    # 数据库交互
    # 实例化 Students 模型对象
    print(url_for('hello_view'))
    return {"code": "0", "msg": "success"}


if __name__ == '__main__':
    app.run()

url_for('hello_view') 通过视图函数,可以反向得到 url 地址 /api/v1/hello

endpoint 参数

上面了解了 url_for() 函数的使用,接着看 endpoint 参数的使用,endpoint 相当于给视图函数取一个别名

@app.route('/api/v1/hello', endpoint="hello")
def hello_view():
    # 数据库交互
    # 实例化 Students 模型对象
    print(url_for('hello_view'))
    return {"code": "0", "msg": "success"}

当加了 endpoint 参数, url_for() 函数如果获取视图函数名称会报错

Could not build url for endpoint 'hello_view'. Did you mean 'hello' instead?

也就是只能通过endpoint 设置的名称来反向获取视图函数的url地址了

@app.route('/api/v1/hello', endpoint="hello")
def hello_view():
    # 数据库交互
    # 实例化 Students 模型对象
    print(url_for('hello'))
    return {"code": "0", "msg": "success"}

此时通过hello 名称可以获取到 url 地址 '/api/v1/hello'。

总结:
url_for() 相当于 django 中的 reverse() 函数,endpoint 参数相当于 django 中的 name 参数。
如果我们不指定endpoint,则 endpoint 默认等于视图函数名, 如果指定了endpoint参数,那么url_for() 需传endpoint 的值。

posted @ 2022-08-27 18:15  上海-悠悠  阅读(474)  评论(0编辑  收藏  举报