请求开始
from flask import Flask
app=Flask(__name__)
if __name__==__main__:
app.__call__
app.run()
1,请求进来时执行app__call__方法,调用def wsgi_app(self, environ, start_response)
environ封装了所有的请求信息.
def wsgi_app(self, environ, start_response): ctx = self.request_context(environ) ctx.push() error = None try: try: response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: error = sys.exc_info()[1] raise return response(environ, start_response) finally: if self.should_ignore_error(error): error = None ctx.auto_pop(error)
==> ctx = self.request_context(environ)
def __init__(self, app, environ, request=None): self.app = app if request is None: request = app.request_class(environ) self.request = request self.url_adapter = app.create_url_adapter(self.request) self.flashes = None self.session = None .... if request is None: request = app.request_class(environ) self.request = request 当没有request进来时,执行request_class方法,把数据封装BaseRequest类中
==> ctx.push()
top = _request_ctx_stack.top #从请求中拿出函数 if top is not None and top.preserved: #没有请求则返回 top.pop(top._preserved_exc) app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: #如果没有请求 app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx) #把函数命令放到列表里,等待后面for循环并执行 else: self._implicit_app_ctx_stack.append(None) if hasattr(sys, ‘exc_clear‘): sys.exc_clear() _request_ctx_stack.push(self) self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session()
==> response = self.full_dispatch_request()
#开始走中间件,视图函数
def full_dispatch_request(self): self.try_trigger_before_first_request_functions() #执行中间件 try: #视图函数开始,发送信号 request_started.send(self) #发送信号,表示开始运行函数进入中间件. 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 finalize_request(self, rv, from_error_handler=False):
函数执行完成最后走这里
response = self.make_response(rv) try: response = self.process_response(response) request_finished.send(self, response=response) #最后发送信号 except Exception: if not from_error_handler: raise self.logger.exception(‘Request finalizing failed with an ‘ ‘error while handling an error‘) return response