TransmittableThreadLocal 获取用户
时间: 2023-12-15 14:33:04 浏览: 87
根据提供的引用内容,TransmittableThreadLocal主要是为了解决子父线程不能共用变量的问题。在获取用户信息时,我们可以将用户信息通过set方法放入TransmittableThreadLocal这个线程中,这样就可以保证在异步方法执行前后线程的改变不会影响到当前登录用户的信息。具体实现可以参考以下代码:
```python
from concurrent.futures import ThreadPoolExecutor
from threading import current_thread
from threading import Thread
from threading import get_ident
from threading import local
from six.moves import _thread as thread
class TransmittableThreadLocal(local):
def __init__(self):
self.__dict__['_local'] = {}
def __getattr__(self, name):
try:
return self._local[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self._local[name] = value
def __delattr__(self, name):
del self._local[name]
def clear(self):
self._local.clear()
def __copy__(self):
return self
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__.update(state)
def get_ident(self):
return get_ident()
def get_thread(self):
return current_thread()
def main_thread(self):
return thread.get_ident() == self.get_ident()
def run_with(self, **kwargs):
return _patch_thread_local(self._local, kwargs)
def patch_thread_local(self, **kwargs):
return _patch_thread_local(self._local, kwargs)
def __repr__(self):
return '<%s.%s object at %x>' % (
self.__class__.__module__,
self.__class__.__qualname__,
id(self),
)
def _patch_thread_local(local_dict, patch_dict):
# Save the original thread-local values.
orig_values = {}
for key in patch_dict:
orig_values[key] = local_dict.get(key, None)
# Patch the thread-local values.
local_dict.update(patch_dict)
# Run the wrapped function.
try:
yield
finally:
# Restore the original thread-local values.
for key in patch_dict:
local_dict[key] = orig_values[key]
if orig_values[key] is None:
del local_dict[key]
# 示例代码
def get_user_info():
user_info = {'name': '张三', 'age': 18}
local_data = TransmittableThreadLocal()
local_data.user_info = user_info
print('当前线程:', current_thread().name)
print('当前用户信息:', local_data.user_info)
# 使用线程池执行异步任务
with ThreadPoolExecutor(max_workers=2) as executor:
for i in range(2):
executor.submit(get_user_info)
```
阅读全文