flask 源码专题(八):路由加载
1.示例代码
from flask import Flask app = Flask(__name__,static_url_path='/xx') @app.route('/index') def index(): return 'hello world
2.路由加载源码分析
2.1先执行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
2.2 执行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中找到别名对应的视图函数
本文来自博客园,作者:秋华,转载请注明原文链接:https://www.cnblogs.com/qiu-hua/p/12637748.html