LocalStack 对象维护栈

模拟

  1. import threading
  2. """
  3. storage = {
  4. 1232: {stack:[123,456]}
  5. }
  6. """
  7. class Local(object):
  8. def __init__(self):
  9. object.__setattr__(self, 'storage', {})
  10. def __setattr__(self, key, value):
  11. ident = threading.get_ident() # 1233
  12. if ident in self.storage:
  13. self.storage[ident][key] = value
  14. else:
  15. self.storage[ident] = {key: value}
  16. def __getattr__(self, item):
  17. ident = threading.get_ident()
  18. if ident not in self.storage:
  19. return
  20. if item not in self.storage[ident]:
  21. return
  22. return self.storage[ident][item]
  23. class LocalStack(object):
  24. def __init__(self):
  25. self._local = Local()
  26. def push(self, value):
  27. """
  28. 将值放入栈
  29. :param value:
  30. :return:
  31. """
  32. re = self._local.stack
  33. if re:
  34. self._local.stack.append(value)
  35. else:
  36. self._local.stack = [value,]
  37. return re
  38. def pop(self,):
  39. """
  40. 从栈中拿走值
  41. :return:
  42. """
  43. if not self._local.stack:
  44. return
  45. if len(self._local.stack) == 1:
  46. data = self._local.stack.pop()
  47. # 当stack中的元素为1时,执行pop操作后,要销毁stack,这里暂时没有做
  48. return data
  49. else:
  50. return self._local.stack.pop()
  51. def top(self):
  52. """
  53. 查看栈顶的数据
  54. :return:
  55. """
  56. if not self._local.stack:
  57. return
  58. return self._local.stack[-1]
  59. st = LocalStack()
  60. st.push(123)
  61. st.push(456)
  62. a = st.top()
  63. b = st.pop()
  64. b = st.pop()
  65. # # b = st.pop()
  66. a = st.top()
  67. print(b,a)

源码展示

LocalStack部分

  1. class LocalStack(object):
  2. """This class works similar to a :class:`Local` but keeps a stack
  3. of objects instead. This is best explained with an example::
  4. >>> ls = LocalStack()
  5. >>> ls.push(42)
  6. >>> ls.top
  7. 42
  8. >>> ls.push(23)
  9. >>> ls.top
  10. 23
  11. >>> ls.pop()
  12. 23
  13. >>> ls.top
  14. 42
  15. They can be force released by using a :class:`LocalManager` or with
  16. the :func:`release_local` function but the correct way is to pop the
  17. item from the stack after using. When the stack is empty it will
  18. no longer be bound to the current context (and as such released).
  19. By calling the stack without arguments it returns a proxy that resolves to
  20. the topmost item on the stack.
  21. .. versionadded:: 0.6.1
  22. """
  23. def __init__(self):
  24. self._local = Local()
  25. def __release_local__(self):
  26. self._local.__release_local__()
  27. def _get__ident_func__(self):
  28. return self._local.__ident_func__
  29. def _set__ident_func__(self, value):
  30. object.__setattr__(self._local, "__ident_func__", value)
  31. __ident_func__ = property(_get__ident_func__, _set__ident_func__)
  32. del _get__ident_func__, _set__ident_func__
  33. def __call__(self):
  34. def _lookup():
  35. rv = self.top
  36. if rv is None:
  37. raise RuntimeError("object unbound")
  38. return rv
  39. return LocalProxy(_lookup)
  40. def push(self, obj):
  41. """Pushes a new item to the stack"""
  42. rv = getattr(self._local, "stack", None)
  43. if rv is None:
  44. self._local.stack = rv = []
  45. rv.append(obj)
  46. return rv
  47. def pop(self):
  48. """Removes the topmost item from the stack, will return the
  49. old value or `None` if the stack was already empty.
  50. """
  51. stack = getattr(self._local, "stack", None)
  52. if stack is None:
  53. return None
  54. elif len(stack) == 1:
  55. release_local(self._local)
  56. return stack[-1]
  57. else:
  58. return stack.pop()
  59. @property
  60. def top(self):
  61. """The topmost item on the stack. If the stack is empty,
  62. `None` is returned.
  63. """
  64. try:
  65. return self._local.stack[-1]
  66. except (AttributeError, IndexError):
  67. 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. CSS3媒体查询实例

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. nginx中location的顺序(优先级)及rewrite规则写法

    一.location正则写法 一个示例: location = / { # 精确匹配 / ,主机名后面不能带任何字符串 [ configuration A ] } location / { # 因为所 ...

  3. javascript逻辑非(!/!!)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. SpringBoot+JTA+Mybatis

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/sinat_36596988/article ...

  5. pwrite,pread

    pwrite,pread,在多线程中读写文件使用,将lseek 和read 或write 合为一个原子操作(在执行的时候不会失去CPU). ssize_t pwrite(intfd, const vo ...

  6. DE2-115 以太网通信之一88E1111网卡接收PC数据

    想利用手头上的DE2-115 写一个关于以太网通信的驱动,经过了这么多天的实验调试终于有了一些认识. 1.我在观察网卡发送数据与接收数据的过程中发现,我从fpga上的一个网卡发送数据,然后另一个网卡接 ...

  7. 【线性代数】6-7:SVD分解(Singular Value Decomposition-SVD)

    title: [线性代数]6-7:SVD分解(Singular Value Decomposition-SVD) categories: Mathematic Linear Algebra keywo ...

  8. redhat7.4安装gitlab

    1.参考官方安装指南 https://about.gitlab.com/install/#centos-7 2.遇到的问题 2.1.启动postfix出错 错误内容 Job for postfix.s ...

  9. 【转】CAtlRegExp class .

    CAtlRegExp Class   CAtlRegExp 类用于表示并处理正则表达式.模板类,定义如下:     template < class CharTraits = CAtlRECha ...

  10. 设置Python打印格式

    >>> def esc(code): ... return f'\033[{code}m' ... >>> print(esc('31;1;4') + 'reall ...