前言
在上一篇中,从最简单使用形式入手,简单的过了一遍Flask应用启动流程以及其背后的原理,本篇将会以类似的风格剖析Flask路由相关的内容,同样不会涉及过多细节,力求从较高的维度去看。
Flask版本:1.0.2
endpoint端点
回归一下上一篇文章,在通过@app.route()装饰器将函数转为Flask视图函数时,多次提及了endpoint,对应的add_url_rule()代码如下。
# flask/app.py/Flask
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
methods = options.pop('methods', None)
rule = self.url_rule_class(rule, methods=methods, **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
在add_url_rule()方法中通过endpoint,将路由与视图函数关联在一起,为什么不直接将路由与视图函数关联?要多弄个endpoint?
为了回答这个问题,先来了解一下endpoint。
通常,可以通过两种方式将路由与视图函数关联。
@app.route('/hello/<name>')
def hello(name):
return f'Hello, {name}!'
或