利用werkzeug实现线程隔离的全局变量
1. 需求
编码过程中,当函数的调用层级很深时,如果从上层一级级把参数传递进去,往往显得繁琐而且丑陋,所以希望换种方式
2. 目录结构
$ ls
local_var.py test.py
3. 代码
# local_var.py
from werkzeug import Local
_local = Local()
class _Local:
def __init__(self, key, value):
self._local = _local
self._key = key
self._value = value
def __enter__(self):
setattr(self._local, self._key, self._value)
def __exit__(self, *args):
delattr(self._local, self._key)
def get_var(name):
return getattr(_local, name, None)
def exec_with_var(name, value, func, *args, **kwargs):
with _Local(name, value):
return func(*args, **kwargs)
# test.py
import local_var
def func():
value = local_var.get_var('test')
if value is None:
print(':bad:', value)
else:
print(':good:', value)
if __name__ == "__main__":
func()
local_var.exec_with_var('test', 'test-value', func)
func()
4. 测试
$ python test.py
:bad: None
:good: test-value
:bad: None