码迷,mamicode.com
首页 > 其他好文 > 详细

flask源代码笔记——路由

时间:2017-09-14 18:35:37      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:dispatch   pat   请求   __call__   one   tar   star   none   force   

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源代码笔记——路由

标签:dispatch   pat   请求   __call__   one   tar   star   none   force   

原文地址:http://www.cnblogs.com/tdkihrr/p/7521562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!