flask源代码笔记——路由
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask源代码笔记——路由相关的知识,希望对你有一定的参考价值。
def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) def wsgi_app(self, environ, start_response): with self.request_context(environ): rv = self.preprocess_request() if rv is None: rv = self.dispatch_request() response = self.make_response(rv) response = self.process_response(response) return response(environ, start_response)
这里处理请求时用到了几个方法:
preprocess_request(),用来处理before_request_funcs这个字典里的函数:
def preprocess_request(self): for func in self.before_request_funcs: rv = func() if rv is not None: return rv
make_response(),将视图函数返回的值转换为真正的响应对象(一个response_class类的实例):
def make_response(self, rv): if isinstance(rv, self.response_class): return rv if isinstance(rv, basestring): return self.response_class(rv) if isinstance(rv, tuple): return self.response_class(*rv) return self.response_class.force_type(rv, est.environ) def process_response(self, response): session = _request_ctx_stack.top.session if session is not None: self.save_session(session, response) for handler in self.after_request_funcs: response = handler(response) return response
这段代码最核心的部分是dispatch_request(),用来将请求分发到对应的视图函数。
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) def match_request(self): rv = _request_ctx_stack.top.url_adapter.match() request.endpoint, request.view_args = rv return rv _request_ctx_stack = LocalStack()
LocalStack是从werkzeug中导入的,如它的名字所示,它是一个栈:
>>> ls = LocalStack() >>> ls.push(42) >>> ls.top 42 >>> ls.push(23) >>> ls.top 23 >>> ls.pop() 23 >>> ls.top 42
可它这个栈不仅有栈的特性,也和class:`Local`很相似。
以上是关于flask源代码笔记——路由的主要内容,如果未能解决你的问题,请参考以下文章