之前读到 app.route
实际上是调用 add_url_rule
函数,主要做了两件事:
- 注册
view_func
到Flask实例
- 建立一个Rule实例,绑定Rule实例到Map实例
那收到一个匹配Map中某个Rule之后,怎么再call到原来的 view_func
呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| def match_request(self): rv = _request_ctx_stack.top.url_adapter.match() request.endpoint, request.view_args = rv return rv
def dispatch_request(self): try: endpoint, values = self.match_request() return self.view_functions[endpoint](**values)
except HTTPException, e: handler = self.error_handlers.get(e.code) if handler is None: return e return handler(e)
except Exception, e: handler = self.error_handlers.get(500) if self.debug or handler is None: raise return handler(e)
|
从这里可以知道,Flask每收到一次request时,都会遍历一次map, 执行map中每个rule的match函数,根据request路径进行匹配,如果匹配成功则获得endpoint和参数,再根据字典获得view_func,并传入参数。