简单记录flask路由原理

简单记录flask路由原理

十二月 10, 2019 阅读 164 字数 978 评论 0 喜欢 0

一、添加url方式

1、@app.route(‘xxx’)(实际route方法本质上还是调用了add_url_rule方法)

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、app.add_url_rule(‘xxx’, view_func=demo)

def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
    """Connects a URL rule.  Works exactly like the :meth:`route`
    decorator.  If a view_func is provided it will be registered with the
    endpoint.
    """

    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

二、原理

  • url和视图函数通过endpoint关联起来。url<---->endpoint<---->view_func;

  • url和endpoint的对应关系存入到url_map中;

  • 以endpoint为key,view_function为值存入view_functions字典中。

  • 添加url的两种方法都可以指定endpoint,如果endpoint未指定,会把视图函数的名称做为默认的endpoint的值。

发表评论

电子邮件地址不会被公开。 必填项已用*标注