if __name__ == '__main__':
app.run() #函数入口 -->调用 app.__call__
整个流程如下
globals.py 全局变量文件,这个是在启动之前启动
_request_ctx_stack = LocalStack()app.__call__
--> wsgi_app
-->ctx =request_context() --> RequestContext() --> app.request_class(environ)-->Request 实例化过程
-->ctx.push() -->_request_ctx_stack.push(self) -->LocalStack().push-->Local().__setattr__ 请求进入时
-->ctx.auto_pop(error) -->_request_ctx_stack.pop()-->LocalStack().pop -->Local(). __delattr__ 请求离开
代码具体流程如下,
数据1.x 的为实例化过程
数字2.x 为请求进入的流程
数字3.x 为请求离开时的流程
globals.py 全局变量文件,这个是在启动之前启动 2.3 _request_ctx_stack = LocalStack() local.py class LocalStack(object): def __init__(self): self._local = Local() #实例化 2.4 def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, 'stack', None) if rv is None: # 执行了local的 __setattr__方法 # v =[] # self._local =v # rv = v self._local.stack = rv = [] #obj 就是 requestContext对象(ctx) rv.append(obj) return rv 3.4 def pop(self): stack = getattr(self._local, 'stack', None) if stack is None: return None elif len(stack) == 1: release_local(self._local) return stack[-1] else: return stack.pop() class Local(object): def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) 2.5 def __setattr__(self, name, value): #name = stack #value = [] #storage { 唯一ID : { stack : [obj,] } } ident = self.__ident_func__() #获取唯一的id storage = self.__storage__ #storage 字典 try: storage[ident][name] = value except KeyError: storage[ident] = {name: value} 3.5 def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) 入口: app.py class Flask(): 1.1 app.__call__ 1.2 def wsgi_app(self, environ, start_response): 1.3 ctx = self.request_context(environ) 2.1 ctx.push() #进 3.1 ctx.auto_pop(error)出 1.6 request_class = Request #调用wrappers.py Request 类 1.4 def request_context(self, environ): return RequestContext(self, environ) ctx.py class RequestContext(object): def __init__(self, app, environ, request=None): 1.5 request = app.request_class(environ) def push(self): 2.2 _request_ctx_stack.push(self) 3.2 def pop(self, exc=_sentinel): rv = _request_ctx_stack.pop() wrappers.py class Request(RequestBase, JSONMixin): 1.7 def __init__():