Flask源码:app.py (二)Request到视图函数

    def __call__(self, environ, start_response):
        #WSGI框架直接调用App对象作为WSGI应用,作为责任链模式调用的接口
        return self.wsgi_app(environ, start_response)
    
    def wsgi_app(self, environ, start_response):
         """实际的 WSGI 应用. 不在__call__实现的原因是要添加中间件的话,
        使用这种方法可以更加明确一些,代替用这种方法添加中间件

            app = MyMiddleware(app)

        而是用这种方法添加

            app.wsgi_app = MyMiddleware(app.wsgi_app)

        """
        
        #def request_context(self, environ):
        #    return RequestContext(self, environ)
        #主要是对global.py中_request_ctx_stack的一个封装,实际函数在ctx.py中
        ctx = self.request_context(environ)
        error = None
        try:
            try:
                ctx.push()    #将环境上下文压入栈中
                response = self.full_dispatch_request()#分发请求
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:  # noqa: B001
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)            #工厂模式
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)

    def full_dispatch_request(self):
        #默认调用使用before_first_request方法添加的一系列函数
        self.try_trigger_before_first_request_functions()
        try:
            request_started.send(self)    #request_started信号
            rv = self.preprocess_request()    #预处理与蓝图相关
            if rv is None:
                rv = self.dispatch_request()    #分发至视图函数
        except Exception as e:
            rv = self.handle_user_exception(e)    #异常处理
        return self.finalize_request(rv)    #封装视图函数处理结果

    def dispatch_request(self):
        #获取全局Request栈顶上下文
        req = _request_ctx_stack.top.request
        #有路由异常
        if req.routing_exception is not None:
            self.raise_routing_exception(req)
        rule = req.url_rule

        if (
            getattr(rule, "provide_automatic_options", False)
            and req.method == "OPTIONS"
        ):    #OPTIONS方法原子操作默认处理
            return self.make_default_options_response()
        #调用视图函数
        return self.view_functions[rule.endpoint](**req.view_args)
发布了23 篇原创文章 · 获赞 0 · 访问量 2012

猜你喜欢

转载自blog.csdn.net/qq_33913982/article/details/104257072