阅读背景:

flask上下文相关-LocalStack 对象维护栈

来源:互联网 

LocalStack 对象维护栈

模拟

import threading

"""
storage = {
   1232: {stack:[123,456]}
}
"""

class Local(object):
    def __init__(self):
        object.__setattr__(self, 'storage', {})

    def __setattr__(self, key, value):
        ident = threading.get_ident()  # 1233
        if ident in self.storage:
            self.storage[ident][key] = value
        else:
            self.storage[ident] = {key: value}

    def __getattr__(self, item):
        ident = threading.get_ident()
        if ident not in self.storage:
            return
        if item not in self.storage[ident]:
            return
        return self.storage[ident][item]


class LocalStack(object):

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


    def push(self, value):
        """
        将值放入栈
        :param value:
        :return:
        """
        re = self._local.stack
        if re:
            self._local.stack.append(value)
        else:
            self._local.stack = [value,]
        return re

    def pop(self,):
        """
        从栈中拿走值
        :return:
        """
        if not self._local.stack:
            return
        if len(self._local.stack) == 1:
            data = self._local.stack.pop()
            # 当stack中的元素为1时,执行pop操作后,要销毁stack,这里暂时没有做
            return data
        else:
            return self._local.stack.pop()


    def top(self):
        """
        查看栈顶的数据
        :return:
        """
        if not self._local.stack:
            return
        return self._local.stack[-1]



st = LocalStack()
st.push(123)
st.push(456)
a = st.top()
b = st.pop()
b = st.pop()
# # b = st.pop()
a = st.top()
print(b,a)import threading

"""
st



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: