上下文管理

对于上下文管理我没有找到明确的定义,但是经过源码流程的学习后,我觉得所谓的上下文管理应该就是Flask对请求和应用相关数据的一种处理方式,它不是像Django一样通过参数的传导,而是创建了全局变量直接引用,Flask为每个线程开辟一块独立的内存空间,将请求和应用相关的信息放到这个空间中,全局变量直接从这个空间中取出数据。

 

一、上下文管理流程梳理:

Python 21 Flask(二)上下文管理详解

 

二、上下文管理图示:

Python 21 Flask(二)上下文管理详解

 

三、源码分析

try:
    from greenlet import getcurrent as get_ident
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident


class Local(object):
    __slots__ = ("__storage__", "__ident_func__")    #表示只能有这两个变量

    def __init__(self):
        object.__setattr__(self, "__storage__", {})
        object.__setattr__(self, "__ident_func__", get_ident)    #这里调用父类的方法

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

    def __call__(self, proxy):
        """Create a proxy for a name."""
        return LocalProxy(self, proxy)

    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
        except KeyError:
            storage[ident] = {name: value}

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
相关资源
相似解决方案