flask的request和session设置方式比较新颖,如果没有这种方式,那么就只能通过参数的传递。

flask是如何做的呢?

1.Python 实现的本地线程

保证即使是多个线程,自己的值也是互相隔离。

import threading
 
local_values = threading.local()
 
 
def func(num):
    local_values.name = num
    import time
    time.sleep(1)
    print(local_values.name, threading.current_thread().name)
 
 
for i in range(20):
    th = threading.Thread(target=func, args=(i,), name='线程%s' % i)
    th.start()

 3. Flask内部实现的本地线程

Flask源码

自定义类似于本地线程
from flask import session

try:
    from greenlet import getcurrent as get_ident
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident # 获取线程的唯一标识 get_ident()

class Local(object):
    __slots__ = ('__storage__', '__ident_func__')

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

    def __iter__(self):
        return iter(self.__storage__.items())

    def __release_local__(self):
        self.__storage__.pop(self.__ident_func__(), None)

    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 # { 111:{'stack':[] },222:{'stack':[] }  }
        except KeyError:
            storage[ident] = {name: value}

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

_local = Local()
_local.stack = []
Local

相关文章:

  • 2022-12-23
  • 2022-01-30
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案