资讯专栏INFORMATION COLUMN

从app.route装饰器引发对endpoint的思考

妤锋シ / 1790人阅读

摘要:为字段赋值,返回给客户端进行重定向总结一个视图函数的如果不设置那么就是视图函数名。为和搭起桥梁,使得整个后端框架更加灵活。返回的是视图函数对应的,是对应视图函数装饰器传入的值。

还是先来看看源码

def route(self, rule, **options):
    """A decorator that is used to register a view function for a
    given URL rule.  This does the same thing as :meth:`add_url_rule`
    but is intended for decorator usage::

        @app.route("/")
        def index():
            return "Hello World"

    For more information refer to :ref:`url-route-registrations`.

    :param rule: the URL rule as string
    :param endpoint: the endpoint for the registered URL rule.  Flask
                     itself assumes the name of the view function as
                     endpoint
    :param options: the options to be forwarded to the underlying
                    :class:`~werkzeug.routing.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.
    """
    def decorator(f):
        endpoint = options.pop("endpoint", None)
        self.add_url_rule(rule, endpoint, f, **options)
        return f
    return decorator

route传入了**options这样一个字典,一般我们会传方法methods进去,GET、POST,如果不自己设置endpoint=....的话默认就是No。
然后进入add_url_rule函数看一看:

def add_url_rule(self, rule, endpoint=None, view_func=None, **options):

    if endpoint is None:
        endpoint = _endpoint_from_view_func(view_func)
    options["endpoint"] = endpoint
    methods = options.pop("methods", None)

...
...
...

    self.url_map.add(rule)
    if view_func is not None:
        old_func = self.view_functions.get(endpoint)
        if old_func is not None and old_func != view_func:
            raise AssertionError("View function mapping is overwriting an "
                                 "existing endpoint function: %s" % endpoint)
        self.view_functions[endpoint] = view_func

这里我截取了一些重点的,可以看到如果endpoint为None,会调用_endpoint_from_view_func函数来给endpoint赋值,
看一下_endpoint_from_view_func的代码:

def _endpoint_from_view_func(view_func):

"""Internal helper that returns the default endpoint for a given
function.  This always is the function name.
"""
assert view_func is not None, "expected view func if endpoint " 
                              "is not provided."
return view_func.__name__

可以看到将视图函数名赋值给了endpoint,所以如果我们创建视图函数时不在**options中指明endpoint的话,默认就是视图函数名,
后半部分进行了判断,保证了endpoint的唯一,并将view_func保存在view_functions这个字典中,并且和endpoint形成映射关系,还将路径加入到当前应用中, 这样做的好处是,当我们用url_for()从一个endpoint来找到一个URL时,可以顺着这个映射关系来找,而不用写URL, 常见的用法是url_for(blueprint.endpoint,parm=val...)进行重定向,这样可以获取一个视图函数的路径,传给redirect(),
redirect(location,code=302)函数会把接收的参数作为响应body中的Location字段返回给客户端,并且默认是302临时重定向。

def redirect(location, code=302, Response=None):
...
...

#为Location字段赋值,返回给客户端进行重定向
response.headers["Location"] = location
        return response

总结:
URL《————》endpoint《————》view
一个视图函数的endpoint如果不设置那么就是视图函数名。
为URL和view搭起桥梁,使得整个后端框架更加灵活。
url_for(.endpoint)返回的是视图函数对应的URL,URL是对应视图函数装饰器传入的值。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/44735.html

相关文章

  • flask route设计思路

    摘要:引言本文主要梳理了源码中的设计思路。协议将处理请求的组件按照功能及调用关系分成了三种。不论是什么,最终都会调用函数。 引言 本文主要梳理了flask源码中route的设计思路。首先,从WSGI协议的角度介绍flask route的作用;其次,详细讲解如何借助werkzeug库的Map、Rule实现route;最后,梳理了一次完整的http请求中route的完整流程。 flask rou...

    vvpale 评论0 收藏0
  • Python装饰-装饰流程,执行顺序

    摘要:最近看到一个关于的题文章其中的一个是装饰器的顺序问题就想写篇博客回顾下装饰器首先强烈推荐很久之前看的一篇博文翻译理解中的装饰器关于什么是装饰器看这篇文章就好了这里主要想写关于多个装饰器的执行流程装饰顺序示例代码初始化初始化输出结果初始化初始 最近看到一个关于Flask的CTF(RealWorld CTF 2018 web题bookhub)文章其中的一个trick是装饰器的顺序问题,就想...

    cpupro 评论0 收藏0
  • Flask注册视图函数

    摘要:键是函数名,值是函数对象,函数名也用于生成。注册一个视图函数,用装饰器。获取储存视图函数字典中的函数对象视图函数类中的字典储存了注册的视图函数名和视图函数对象。输出视图函数视图函数名重复修改解决 那天莫名其妙出了个错。。就顺便看了看Flask路由 在flask存储路由函数是以函数名为键,函数对象为值 class Flask: def __init__(self, *args, ...

    2bdenny 评论0 收藏0
  • flask之三:视图高级

    摘要:视图高级和这个方法是用来添加与视图函数的映射。小例子如下请求上下文的定义,结合类视图之前我们接触的视图都是函数,所以一般简称视图函数。 视图高级 app.route和app.add_url_rule app.add_url_rule app.add_url_rule(/list/,endpoint=myweb,view_func=my_list) 这个方法是用来添加url与视图函数...

    hot_pot_Leo 评论0 收藏0
  • flask之三:视图高级

    摘要:视图高级和这个方法是用来添加与视图函数的映射。小例子如下请求上下文的定义,结合类视图之前我们接触的视图都是函数,所以一般简称视图函数。 视图高级 app.route和app.add_url_rule app.add_url_rule app.add_url_rule(/list/,endpoint=myweb,view_func=my_list) 这个方法是用来添加url与视图函数...

    RancherLabs 评论0 收藏0

发表评论

0条评论

妤锋シ

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<