LocalStack源碼
class LocalStack(object):
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
雖然Local是通過(guò)key-value管理對(duì)象席怪,但是LocalStack引入了類(lèi)型為list的stack纤控,這樣看起來(lái)像stack船万。
"""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
另外__call__
的實(shí)現(xiàn),使得每次調(diào)用拿的都是最新push的對(duì)象声怔。
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError("object unbound")
return rv
return LocalProxy(_lookup)
使用LocalStack
from werkzeug.local import LocalStack
class Request(object):
def __init__(self):
self.url = 'baidu.com'
class User(object):
def __init__(self):
self.owner = 'www'
request = Request()
user = User()
ls = LocalStack()
ls.push(request)
r = ls()
print(r)
ls.push(user)
# 特別注意的是這里是User對(duì)象醋火,調(diào)用__call__
r = ls()
print(r)
輸出結(jié)果:
<main.Request object at 0x7f1566d42e10>
<main.User object at 0x7f1566d42da0>
拿到了Request和User對(duì)象實(shí)例箱吕。