06 Flask源码之:路由加载
1.示例代码
from flask import Flask
app = Flask(__name__,static_url_path='/xx')
@app.route('/index')
def index():
return 'hello world'
2.路由加载源码分析
-
先执行route函数
def route(self, rule, **options): def decorator(f): endpoint = options.pop("endpoint", None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
-
执行
add_url_rule
函数def add_url_rule( self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options ): if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options["endpoint"] = endpoint methods = options.pop("methods", None) if methods is None: methods = getattr(view_func, "methods", None) or ("GET",) rule = self.url_rule_class(rule, methods=methods, **options) self.url_map.add(rule) if view_func is not None: self.view_functions[endpoint] = view_func
- 将
url = /index
和methods = [GET,POST]
和endpoint = "index"
封装到Rule对象 - 将Rule对象添加到
app.url_map
中。 - 把endpoint和函数的对应关系放到
app.view_functions
中。 - 当一个请求过来时,先拿路由在app.url_map找对应的别名,再在app.view_functions中找到别名对应的视图函数
- 将