Flask之请求源码分析 上下文管理
从请求进来到出去的整体流程


盏:先进后出, 维护的盏即是那个 列表,和里边的内容, 会用到pop 和从 -1索引取值
请求的顺序:


Local类的作用:可以开多线程:每个线程都有他的唯一标识{1244:{stack:[ctx,]},1897:{stack:[ctx,]}},给每个线程隔离开来,不会引起当前多个请求挨着时候触发时,
后边完成的请求把前边请求中的session ,request中的信息顶替掉
最后阶段

request,current_app,g中的内容随着请求结束,也就被销毁了
session Flask会吧session放到(保存到)浏览器的cookie中去,当请求再过来 会带着这些信息
AppContext對 app和g进行封装,也是在封装request和session 的同时执行的




有几个类: 这里个类的原形
1

客户端发送请求,然后走到这儿

进去看下app.__call__ 可以看到这里有wsgi处理过的 environ 初级的处理

进到这函数

进入到上边的函数会先执行 request_context()

进入到函数中去

看看这个类对request和session进行了那些处理

初步处理后的结果


执行ctx.push()




push中还有一个操作给session重新赋值的操作

第二阶段
继续往下走


进去之后出来 判断是否处理完成



LocalProxy类中有此方法
![]()
![]()

源码分析之第二阶段,视图函数中的请求相关的内容的处理
#encoding=utf-8 from flask import Flask,request app=Flask(__name__,template_folder='templates',)#一个flask类的对象 @app.route('/login',methods=["GET","POST"]) def login(): #要打印request.method 1 先进入到request的源码中去看一下 print(request.method) #这个request实际是LocalProxy的实例化对象, # 果如想要调用request.method实际就是在调用request这个对象的getattr的方法 request = LocalProxy(partial(_lookup_req_object, 'request')) #继续往下看,这里边有一个偏函数,传入的参数是request partial(_lookup_req_object, 'request') def _lookup_req_object(name): #这个函数需要传参数,但是通过partial方法默认给他穿了一个“request” top = _request_ctx_stack.top if top is None: raise RuntimeError(_request_ctx_err_msg) return getattr(top, name) #此函数是从 Local类中去push到线程中的{"stark":ctk(request,session)} 获取 ctk中的request的内容 #传入此函数进到LocalProxy() LocalProxy(request) #进入到此函中 local 指的就是 request了 def __init__(self, local, name=None): #这句话就是self.__local object.__setattr__(self, '_LocalProxy__local', local) object.__setattr__(self, '__name__', name) if callable(local) and not hasattr(local, '__release_local__'): # "local" is a callable that is not an instance of Local or # LocalManager: mark it as a wrapped function. object.__setattr__(self, '__wrapped__', local) def _get_current_object(self): """Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. """ if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__) except AttributeError: raise RuntimeError('no object bound to %s' % self.__name__) #进入到此类中的getattr方法中,执行此方法, def __getattr__(self, name): if name == '__members__': return dir(self._get_current_object()) #将这一步进行分析 #name=method #self._get_current_object()这个得到的内容就是 # 从Local对象中取出来的request #相当于在执行 return getattr(request,method) return getattr(self._get_current_object(), name) def _get_current_object(self): """Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. """ if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__)
第三阶段:处理完请求,的处理



浙公网安备 33010602011771号