Werkzeug的Local系列(4) -Local源码与使用

Local源码

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)

跟之前示例是一样的,

  • 增加了__setattr__动态增加管理的对象
  • ident为线程或者协程ID

所以Local管理的是所有线程的上下文信息。

使用Werkzeug的Local

# 使用werkzeug的Local

from werkzeug.local import Local

l = Local()
l.request = 'request'
print(l.__storage__)

request = l('request')
print(request)

输出结果:

{140610526643968: {'request': 'request'}}
request

你可能感兴趣的:(Werkzeug的Local系列(4) -Local源码与使用)