Flask的endpoint的理解

在flask框架中,我们经常会遇到 endpoint这个东西,最开始也没法理解这个到底是做什么的。最近正好在研究 Flask的源码,也就顺带了解了一下这个 endpoint

1、Flask路由是怎么工作

整个flask框架(及以 _Werkzeug_类库为基础构建的应用)的程序理念是把URL地址映射到你想要运行的业务逻辑上(最典型的就是视图函数),例如:

from flask import Flask
app = Flask(__name__)

@app.route("/index/")
def index1():
    return '{"key1":1,"key2":2}'

注意, _add_url_rule_函数实现了同样的目的,只不过没有使用装饰器,因此,下面的程序是等价的:

def index3():
     return '{"key1":1,"key2":2}'
app.add_url_rule("/index/",view_func=index3)

2、add_url_rule的介绍

这个 add_url_rule函数在文档中是这样解释的:

 def add_url_rule(
        self,
        rule: str,
        endpoint: t.Optional[str] = None,
        view_func: t.Optional[t.Callable] = None,
        provide_automatic_options: t.Optional[bool] = None,
        **options: t.Any,
    )

add_url_rule有如下参数:

rule – the URL rule as string
endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint
view_func – the function to call when serving a request to the provided endpoint
options – the options to be forwarded to the underlying Rule object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly added and handled by the standard request handling.

抛开 options这个参数不谈,我们看看前三个参数。
rule:这个参数很简单,就是匹配的路由地址
view_func:这个参数就是我们写的视图函数
endpoint:这个参数就是我今天重点要讲的, endpoint

很多人认为:假设用户访问 http://www.example.com/user/ericflask会找到该函数,并传递 name='eric',执行这个函数并返回值。
但是实际中, Flask真的是直接根据路由查询视图函数么?

Flask的endpoint的理解

url_map: 维护的是url和endpoint的映射关系

view_functions: 维护的是endpoint和function的映射关系

所以我们可以看出: 这个 url_map 存储的是 urlendpoint 的映射!
回到flask接受用户请求地址并查询函数的问题。实际上,当请求传来一个url的时候,会先通过 rule找到 endpoint(url_map),然后再根据 endpoint再找到对应的 view_func(view_functions)。通常, endpoint的名字都和视图函数名一样。
这时候,这个 endpoint也就好理解了:

实际上这个endpoint就是一个Identifier,每个视图函数都有一个endpoint, 当有请求来到的时候,用它来知道到底使用哪一个视图函数

在实际应用中,当我们需要二条路由路径显示同一个页面的时候,就可以在定义的方法的下面同时使用二个add_url_rule方法,路由地址分别写为” / ” 和” /home “,endpoint分别显示” index “与” index2 “,最后的view_func同时写成一样的index2就行了,最后二条路地址就可以显示同一个页面,

def index2():
    return "hello world"
app.add_url_rule("/",endpoint="index",view_func=index2)
app.add_url_rule("/home",endpoint="index2",view_func=index2)

这是在根目录下显示的效果:

Flask的endpoint的理解

这是在/home目录下显示的效果:

Flask的endpoint的理解

Flask的endpoint的理解

endpoint 没有明显的定义的话,就会使用函数名字作为endpoint
endpoint在view_functions表需要全局唯一
endpoint函数名可以重复

Original: https://blog.csdn.net/weixin_60067160/article/details/122590017
Author: Li-YC
Title: Flask的endpoint的理解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/748520/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球