• FlASK中的endpoint问题


    先贴一点有关的flask代码,时间有限,我慢慢扩充

    以下是flask源码中app.py中add_url_rule的代码。

    主要是view_func  -- endpoint -- url 之间的对应关系。

    flask中,view_func与url并不是直接对应的,是url先找到endpoint, 然后通过endpoint再去找到对应的view_func,一个endpoint只能对应于一个view_func,在注册add_url_rule的时候,如果不指定endpoint,那么endpoint就会默认为函数名字,如果同一个endpoint于多个url注册的话,会有问题,详见代码中,会判断之前已经对应到的跟现在是不是一个,如果不是的话,那么就要抛出异常。然后再去访问这些url当然是肯定不行的啦。有时间会慢慢扩充这部分的内容。

     1     @setupmethod
     2     def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
     3         if endpoint is None:
     4             endpoint = _endpoint_from_view_func(view_func)
     5         options['endpoint'] = endpoint
     6         methods 
     7        if methods is None:
     8             methods = getattr(view_func, 'methods', None) or ('GET',)
     9         if isinstance(methods, string_types):
    10             raise TypeError('Allowed methods have to be iterables of strings, '
    11                             'for example: @app.route(..., methods=["POST"])')
    12         methods = set(item.upper() for item in methods)
    13 
    14         required_methods = set(getattr(view_func, 'required_methods', ()))
    15 
    16         provide_automatic_options = getattr(view_func,
    17             'provide_automatic_options', None)
    18 
    19         if provide_automatic_options is None:
    20             if 'OPTIONS' not in methods:
    21                 provide_automatic_options = True
    22                 required_methods.add('OPTIONS')
    23             else:
    24                 provide_automatic_options = False
    25 
    26         # Add the required methods now.
    27         methods |= required_methods
    28 
    29         rule = self.url_rule_class(rule, methods=methods, **options)
    30         rule.provide_automatic_options = provide_automatic_options
    31 
    32         self.url_map.add(rule)
    33         if view_func is not None:
    34             old_func = self.view_functions.get(endpoint)
    35             if old_func is not None and old_func != view_func:
    36                 raise AssertionError('View function mapping is overwriting an '
    37                                      'existing endpoint function: %s' % endpoint)
    38             self.view_functions[endpoint] = view_func
  • 相关阅读:
    python正则表达式(+ {})(二)
    14丨 HTTP有哪些优点?又有哪些缺点?
    python正则表达式(. *)(一)
    12丨响应状态码该怎么用?
    Fiddler—Fiddler+willow插件应用(十四)
    11丨你能写出正确的网址吗?
    【洛谷P1858】多人背包
    【洛谷P3387】(模板)缩点
    【洛谷P2184】贪婪大陆
    Leetcode: 39. Combination Sum
  • 原文地址:https://www.cnblogs.com/symons1992/p/5024912.html
Copyright © 2020-2023  润新知