Flask---请求上下文源码分析

threading.local

多个线程修改同一个数据,复制多份变量给每个线程用,为每个线程开辟一块空间进行数据存储

不用threading.local

# 不用local
from threading import Thread
import time
lqz = -1
def task(arg):
    global lqz
    lqz = arg
    # time.sleep(2)
    print(lqz)

for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

threading.local使用

from threading import Thread
from threading import local
import time
from threading import get_ident
# 特殊的对象
lqz = local()
def task(arg):
    # 对象.val = 1/2/3/4/5
    lqz.value = arg
    time.sleep(2)
    print(lqz.value)
for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

通过字典自定义threading.local(函数)

from threading import get_ident,Thread
import time
storage = {}
def set(k,v):
    ident = get_ident()
    if ident in storage:
        storage[ident][k] = v
    else:
        storage[ident] = {k:v}
def get(k):
    ident = get_ident()
    return storage[ident][k]
def task(arg):
    set('val',arg)
    v = get('val')
    print(v)

for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

面向对象版

from threading import get_ident,Thread
import time
class Local(object):
    storage = {}
    def set(self, k, v):
        ident = get_ident()
        if ident in Local.storage:
            Local.storage[ident][k] = v
        else:
            Local.storage[ident] = {k: v}
    def get(self, k):
        ident = get_ident()
        return Local.storage[ident][k]
obj = Local()
def task(arg):
    obj.set('val',arg) 
    v = obj.get('val')
    print(v)
for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

通过setattr和getattr实现

from threading import get_ident,Thread
import time
class Local(object):
    storage = {}
    def __setattr__(self, k, v):
        ident = get_ident()
        if ident in Local.storage:
            Local.storage[ident][k] = v
        else:
            Local.storage[ident] = {k: v}
    def __getattr__(self, k):
        ident = get_ident()
        return Local.storage[ident][k]
obj = Local()
def task(arg):
    obj.val = arg
    print(obj.val)
for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

每个对象有自己的存储空间(字典)

from threading import get_ident,Thread
import time
class Local(object):
    def __init__(self):
        object.__setattr__(self,'storage',{})
    def __setattr__(self, k, v):
        ident = get_ident()
        if ident in self.storage:
            self.storage[ident][k] = v
        else:
            self.storage[ident] = {k: v}
    def __getattr__(self, k):
        ident = get_ident()
        return self.storage[ident][k]
obj = Local()
def task(arg):
    obj.val = arg
    obj.xxx = arg
    print(obj.val)
for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

兼容线程和协程

try:
    from greenlet import getcurrent as get_ident
except Exception as e:
    from threading import get_ident
from threading import Thread
import time
class Local(object):
    def __init__(self):
        object.__setattr__(self,'storage',{})
    def __setattr__(self, k, v):
        ident = get_ident()
        if ident in self.storage:
            self.storage[ident][k] = v
        else:
            self.storage[ident] = {k: v}
    def __getattr__(self, k):
        ident = get_ident()
        return self.storage[ident][k]
obj = Local()
def task(arg):
    obj.val = arg
    obj.xxx = arg
    print(obj.val)
for i in range(10):
    t = Thread(target=task,args=(i,))
    t.start()

partial偏函数

#偏函数的第二个部分(可变参数),按原有函数的参数顺序进行补充,参数将作用在原函数上,最后偏函数返回一个新函数
from functools import partial
def test(a,b,c,d):
    return a+b+c+d

tes=partial(test,1,2)
print(tes(3,4))

请求上下文源码分析

请求上下文执行流程(ctx):

-0 flask项目一启动,有6个全局变量
    -_request_ctx_stack:LocalStack对象
    -_app_ctx_stack :LocalStack对象
    -request : LocalProxy对象
    -session : LocalProxy对象
-1 请求来了 app.__call__()---->内部执行:self.wsgi_app(environ, start_response)
-2 wsgi_app()
    -2.1 执行:ctx = self.request_context(environ):返回一个RequestContext对象,并且封装了request(当次请求的request对象),session
    -2.2 执行: ctx.push():RequestContext对象的push方法
        -2.2.1 push方法中中间位置有:_request_ctx_stack.push(self),self是ctx对象
        -2.2.2 去_request_ctx_stack对象的类中找push方法(LocalStack中找push方法)
        -2.2.3 push方法源码:
            def push(self, obj):
        #通过反射找self._local,在init实例化的时候生成的:self._local = Local()
        #Local()flask封装的支持线程和协程的local对象
        # 一开始取不到stack,返回None
        rv = getattr(self._local, "stack", None)
        if rv is None:
            #走到这,self._local.stack=[],rv=[]
            self._local.stack = rv = []
        # 把ctx放到了列表中
        #self._local={'线程id1':{'stack':[ctx,]},'线程id2':{'stack':[ctx,]},'线程id3':{'stack':[ctx,]}}
        rv.append(obj)
        return rv
-3 如果在视图函数中使用request对象,比如:print(request)
    -3.1 会调用request对象的__str__方法,request类是:LocalProxy
    -3.2 LocalProxy中的__str__方法:lambda x: str(x._get_current_object())
        -3.2.1 内部执行self._get_current_object()
        -3.2.2 _get_current_object()方法的源码如下:
            def _get_current_object(self):
        if not hasattr(self.__local, "__release_local__"):
            #self.__local()  在init的时候,实例化的,在init中:object.__setattr__(self, "_LocalProxy__local", local)
            # 用了隐藏属性
            #self.__local 实例化该类的时候传入的local(偏函数的内存地址:partial(_lookup_req_object, "request"))
            #加括号返回,就会执行偏函数,也就是执行_lookup_req_object,不需要传参数了
            #这个地方的返回值就是request对象(当此请求的request,没有乱)
            return self.__local()
        try:
            return getattr(self.__local, self.__name__)
        except AttributeError:
            raise RuntimeError("no object bound to %s" % self.__name__)
        -3.2.3 _lookup_req_object函数源码如下:
            def _lookup_req_object(name):
        #name是'request'字符串
        #top方法是把第二步中放入的ctx取出来,因为都在一个线程内,当前取到的就是当次请求的ctx对象
        top = _request_ctx_stack.top
        if top is None:
            raise RuntimeError(_request_ctx_err_msg)
        #通过反射,去ctx中把request对象返回
        return getattr(top, name)
        -3.2.4 所以:print(request) 实质上是在打印当此请求的request对象的__str__
-4 如果在视图函数中使用request对象,比如:print(request.method):实质上是取到当次请求的reuquest对象的method属性
-5 最终,请求结束执行: ctx.auto_pop(error),把ctx移除掉

 

其他的东西:

-session:
    -请求来了opensession
        -ctx.push()---->也就是RequestContext类的push方法的最后的地方:
            if self.session is None:
        #self是ctx,ctx中有个app就是flask对象,   self.app.session_interface也就是它:SecureCookieSessionInterface()
        session_interface = self.app.session_interface
        self.session = session_interface.open_session(self.app, self.request)
        if self.session is None:
            #经过上面还是None的话,生成了个空session
            self.session = session_interface.make_null_session(self.app)

-请求走了savesession
    -response = self.full_dispatch_request() 方法内部:执行了before_first_request,before_request,视图函数,after_request,savesession
    -self.full_dispatch_request()---->执行:self.finalize_request(rv)-----》self.process_response(response)----》最后:self.session_interface.save_session(self, ctx.session, response)

-请求扩展相关
    before_first_request,before_request,after_request依次执行
-flask有一个请求上下文,一个应用上下文
    -ctx:
        -是:RequestContext对象:封装了request和session
        -调用了:_request_ctx_stack.push(self)就是把:ctx放到了那个位置
    -app_ctx:
        -是:AppContext(self) 对象:封装了当前的app和g
        -调用 _app_ctx_stack.push(self) 就是把:app_ctx放到了那个位置

 

g对象

专门用来存储用户信息的g对象,g的全称的为global

g对象在一次请求中的所有的代码的地方,都是可以使用的

g对象和session的区别

session对象是可以跨request的,只要session还未失效,不同的request的请求会获取到同一个session,但是g对象不是,g对象不需要管过期时间,请求一次就g对象就改变了一次,或者重新赋值了一次

 

 

posted @ 2019-11-13 20:29  Yzy~Yolo  阅读(127)  评论(0编辑  收藏  举报