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)

源码展示

LocalStack部分

class LocalStack(object):
"""This class works similar to a :class:`Local` but keeps a stack
of objects instead. This is best explained with an example:: >>> ls = LocalStack()
>>> ls.push(42)
>>> ls.top
42
>>> ls.push(23)
>>> ls.top
23
>>> ls.pop()
23
>>> ls.top
42 They can be force released by using a :class:`LocalManager` or with
the :func:`release_local` function but the correct way is to pop the
item from the stack after using. When the stack is empty it will
no longer be bound to the current context (and as such released). By calling the stack without arguments it returns a proxy that resolves to
the topmost item on the stack. .. versionadded:: 0.6.1
""" def __init__(self):
self._local = Local() def __release_local__(self):
self._local.__release_local__() def _get__ident_func__(self):
return self._local.__ident_func__ def _set__ident_func__(self, value):
object.__setattr__(self._local, "__ident_func__", value) __ident_func__ = property(_get__ident_func__, _set__ident_func__)
del _get__ident_func__, _set__ident_func__ def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError("object unbound")
return rv return LocalProxy(_lookup) def push(self, obj):
"""Pushes a new item to the stack"""
rv = getattr(self._local, "stack", None)
if rv is None:
self._local.stack = rv = []
rv.append(obj)
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:
release_local(self._local)
return stack[-1]
else:
return stack.pop() @property
def top(self):
"""The topmost item on the stack. If the stack is empty,
`None` is returned.
"""
try:
return self._local.stack[-1]
except (AttributeError, IndexError):
return None

flask上下文管理相关-LocalStack 对象维护栈的更多相关文章

  1. flask上下文管理相关 - threading.local 以及原理剖析

    threading.local 面向对象相关: setattr/getattr class Foo(object): pass obj = Foo() obj.x1 = 123 # object.__ ...

  2. Flask上下文管理、session原理和全局g对象

    一.一些python的知识 1.偏函数 def add(x, y, z): print(x + y + z) # 原本的写法:x,y,z可以传任意数字 add(1,2,3) # 如果我要实现一个功能, ...

  3. Flask上下文管理机制

    前引 在了解flask上下文管理机制之前,先来一波必知必会的知识点. 面向对象双下方法 首先,先来聊一聊面向对象中的一些特殊的双下划线方法,比如__call__.__getattr__系列.__get ...

  4. Flask上下文管理

    一.一些python的知识 1.偏函数 def add(x, y, z): print(x + y + z) # 原本的写法:x,y,z可以传任意数字 add(1,2,3) # 如果我要实现一个功能, ...

  5. Flask 上下文管理

    为什么用threading.local? 我们都知道线程是由进程创建出来的,CPU实际执行的也是线程,那么线程其实是没有自己独有的内存空间的,所有的线程共享进程的资源和空间,共享就会有冲突,对于多线程 ...

  6. Flask 上下文管理-- (session,request,current_app的传递)--类似本地线程实现,以及多app应用

    Flask session,request,current_app的传递 请求上下文的作用 -- 封装请求相关得数据(request,session) 请求上下文 request session re ...

  7. Flask - 上下文管理(核心)

    参考 http://flask.pocoo.org/docs/1.0/advanced_foreword/#thread-locals-in-flask https://zhuanlan.zhihu. ...

  8. Flask上下文管理及源码刨析

    基本流程概述 - 与django相比是两种不同的实现方式. - django/tornado是通过传参数形式实现 - 而flask是通过上下文管理, 两种都可以实现,只不实现的方式不一样罢了. - 上 ...

  9. flask 上下文管理 &源码剖析

    基本流程概述 - 与django相比是两种不同的实现方式. - django/tornado是通过传参数形式实现 - 而flask是通过上下文管理, 两种都可以实现,只不实现的方式不一样罢了. - 上 ...

随机推荐

  1. (三)AppScan扫描策略的选择

    使用 AppScan 进行扫描 针对大型网站的扫描,我们按照戴明环 PDCA 的方法论来进行规划和讨论,建议 AppScan 使用步骤:计划(Plan).执行(Do).检查(check).分析(Ana ...

  2. Dinic 与 SAP(ISAP?) 模板

    发一个最大流模板 DinicDinicDinic //vis为int类型 //sz为总点数 namespace Dinic { inline bool bfs() { int head = 0, ta ...

  3. 用python做数据分析4|pandas库介绍之DataFrame基本操作

    原文地址 怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 今天是5.1号. 这一部分主要学习pandas中基于前面两种数据结构 ...

  4. windows版idea 2018.3.5版 永久激活教程

    1.下载idea并安装:https://download.jetbrains.com/idea/ideaIU-2018.3.5.exe?_ga=2.179947812.1869744014.15658 ...

  5. 【算法进阶-康托展开】-C++

    目录 引入 这位老爷子就是康托 基本概念 康托展开是一个全排列到一个自然数的双射,常用于构建hash表时的空间压缩.设有n个数(1,2,3,4,-,n),可以有组成不同(n!种)的排列组合,康托展开表 ...

  6. 002_STM32程序移植之_DHT11

    1. 测试环境:STM32C8T6 2. 测试模块:DHT11温湿度模块 3. 测试接口: 1. DHT11温湿度模块接口: DS1302引脚 ---------单片机引脚 VCC---------- ...

  7. [Luogu] U18430 萌萌的大河

    https://www.luogu.org/problemnew/show/U18430 思路比较好想 树链剖分 对于1操作 只需将以该点为根的子树打标记,将所有数存入数组排序 每次进行1操作时,判断 ...

  8. error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const

    类中包含信号槽在在类的声明中一定得使用Q_OBJECT.当编译出现问题上述问题时. 解决方法: 1.删除项目中的头文件以及源文件,再添加. 2.在头文件中对该类进行声明,不是使用class mycla ...

  9. Python使用grequests并发发送请求

    目录 前言 grequests简单使用 grequests和requests性能对比 异常处理 前言 requests是Python发送接口请求非常好用的一个三方库,由K神编写,简单,方便上手快.但是 ...

  10. 元祖(tuple)

    元祖和列表几乎是一样的: 列表是可以进行修改的,它可以填加一个元素,也可以移除一个元素,但元祖是不能修改的 如果我们以后想导一个集合,这个集合以后不允许修改,我们用元祖:如何我们想让别人进行修改,我们 ...