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的内部,每个核心对象都会维护二张表

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)

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

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

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

猜你喜欢

转载自blog.csdn.net/weixin_60067160/article/details/122590017