先贴一点有关的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当然是肯定不行的啦。有时间会慢慢扩充这部分的内容。

     @setupmethod
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
if methods is None:
methods = getattr(view_func, 'methods', None) or ('GET',)
if isinstance(methods, string_types):
raise TypeError('Allowed methods have to be iterables of strings, '
'for example: @app.route(..., methods=["POST"])')
methods = set(item.upper() for item in methods) required_methods = set(getattr(view_func, 'required_methods', ())) provide_automatic_options = getattr(view_func,
'provide_automatic_options', None) if provide_automatic_options is None:
if 'OPTIONS' not in methods:
provide_automatic_options = True
required_methods.add('OPTIONS')
else:
provide_automatic_options = False # Add the required methods now.
methods |= required_methods rule = self.url_rule_class(rule, methods=methods, **options)
rule.provide_automatic_options = provide_automatic_options 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
05-11 02:53