Flash 上下文管理

1、Local()

作用:为每个协程或线程创建一个独立的内存空间

储存格式:

{
    唯一标识: {'stack': []}
}

代码

try:
    from greenlet import getcurrent as get_ident
except:
    from threading import get_ident
class Local:
    __slots__ = ('__storage__', '__ident_func__')

    def __init__(self):
        # __storage__ = {1231:{'stack':[]}}
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident)

    def __getattr__(self, name):
        try:
            return self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        ident = self.__ident_func__()
        storage = self.__storage__
        try:
            storage[ident][name] = value
        except KeyError:
            storage[ident] = {name: value}

    def __delattr__(self, name):
        try:
            del self.__storage__[self.__ident_func__()][name]
        except KeyError:
            raise AttributeError(name)

2、LocalStack()

作用:通过栈操作local中的列表,列表中可以储存对象

代码

class LocalStack:
    def __init__(self):
        self._local = Local()

    def push(self,value):
        rv = getattr(self._local, 'stack', None) # self._local.stack =>local.getattr
        if rv is None:
            self._local.stack = rv = [] #  self._local.stack =>local.setattr
        rv.append(value) # self._local.stack.append(666)
        return rv


    def pop(self):
        """Removes the topmost item from the stack, will return the
        old value or `None` if the stack was already empty.
        """
        stack = getattr(self._local, 'stack', None)
        if stack is None:
            return None
        elif len(stack) == 1:
            return stack[-1]
        else:
            return stack.pop()

    def top(self):
        try:
            return self._local.stack[-1]
        except (AttributeError, IndexError):
            return None

3、上下文源码分析(request session)

A  wsgi->app.__call__->wsgi_app->ctx = self.request_context(environ) environ初次封装后的数据
a  封装session request : request_context->RequestContext
b  执行push方法->_request_ctx_stack.push(self) ctx ->_request_ctx_stack = LocalStack()->Local()

 总结:

上下文管理分为:

request上下文管理

app上下文管理

__call__


wsgi_app  --> ctx requestcontent(request, session)
          -->push
              --> ctx LocalStack() --> Local()
              --> app LocalStack() --> Local()    
视图函数      --> app LocalPolicy  
            app --> 函数 --> app LockStack() --> Stack()
            g   --> 函数 --> app LockStack() --> Stack()
          --> ctx LocalPolicy
              request --> 函数 --> LocalStack() --> Stack()
              session --> 函数 --> LocalStack() --> Stack()
请求结束
    执行pop删除 ctx 和 app_ctx


1、g和session的生命周期不一样
session要存储在浏览器的cookie中
2、g和全局变量一致吗?
    - 全局变量项目启动加载
    - g会创建->销毁,全局变量不会

 

posted @ 2019-09-28 22:56  市丸银  阅读(201)  评论(0编辑  收藏  举报