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
  1. 将 url = /index 和 methods = [GET,POST]endpoint = "index"封装到Rule对象
  2. 将Rule对象添加到 app.url_map中。
  3. 把endpoint和函数的对应关系放到 app.view_functions中。
  4. 当一个请求过来时,先拿路由在app.url_map找对应的别名,再在app.view_functions中找到别名对应的视图函数

 

posted @ 2020-04-05 16:27  秋华  阅读(203)  评论(0编辑  收藏  举报