def localstack_demo(): ls = LocalStack() a = ls.push(100) # a.pop() b = ls.push(120) print(a, b) print(ls.pop()) print(ls.pop())
def test_local_release(): """Locals work without manager""" loc = Local() loc.foo = 42 release_local(loc) assert not hasattr(loc, "foo") ls = LocalStack() ls.push(42) release_local(ls) assert ls.top is None
def test_local_stack(): """ 函数的代理 """ ls = LocalStack() for i in range(10): ls.push(i) def get_num(): return ls.pop() # LocalProxy 每次调用get_num函数, 并返回 lp = LocalProxy(get_num) for _ in range(10): print(lp)
def local_proxy_test1(): from werkzeug.local import LocalStack user_stack = LocalStack() user_stack.push({'name': 'Bob'}) user_stack.push({'name': 'John'}) def get_user(): # do something to get User object and return it return user_stack.pop() # 直接调用函数获取user对象 user = get_user() print user['name'] print user['name']
def local_proxy_test2(): from werkzeug.local import LocalStack, LocalProxy user_stack = LocalStack() user_stack.push({'name': 'Bob'}) user_stack.push({'name': 'John'}) def get_user(): # do something to get User object and return it return user_stack.pop() # 通过LocalProxy使用user对象 user = LocalProxy(get_user) print user['name'] print user['name']
def test_local_stack(): """Test the LocalStack""" ident = get_ident() ls = LocalStack() assert ident not in ls._local.__storage__ assert ls.top is None ls.push(42) assert ident in ls._local.__storage__ assert ls.top == 42 ls.push(23) assert ls.top == 23 ls.pop() assert ls.top == 42 ls.pop() assert ls.top is None assert ls.pop() is None assert ls.pop() is None proxy = ls() ls.push([1, 2]) assert proxy == [1, 2] ls.push((1, 2)) assert proxy == (1, 2) ls.pop() ls.pop() assert repr(proxy) == "<LocalProxy unbound>" assert ident not in ls._local.__storage__
def test_coroutine_localstack(self): ctx = LocalStack() patch_local(ctx) @coroutine def other_context(): ctx.push(45) return ctx.top ctx.push(40) fut = asyncio.ensure_future(other_context()) yield from fut self.assertEqual(ctx.top, 40) self.assertNotEqual(ctx.top, fut.result()) self.assertEqual(fut.result(), 45)
def test_custom_idents(): """Local manager supports custom ident functions""" ident = 0 local = Local() stack = LocalStack() mgr = LocalManager([local, stack], ident_func=lambda: ident) local.foo = 42 stack.push({"foo": 42}) ident = 1 local.foo = 23 stack.push({"foo": 23}) ident = 0 assert local.foo == 42 assert stack.top["foo"] == 42 stack.pop() assert stack.top is None ident = 1 assert local.foo == 23 assert stack.top["foo"] == 23 stack.pop() assert stack.top is None
def test_local(): """測試線程""" def get_item(): return test_stack.pop() test_stack = LocalStack() test_stack.push({'abc': '123'}) test_stack.push({'abc': '1234'}) item = get_item() print(item['abc']) print(item['abc']) test_stack = LocalStack() test_stack.push({'abc': '123'}) test_stack.push({'abc': '1234'}) item = LocalProxy(get_item) print(item['abc']) print(item['abc'])
def test1(): stack = LocalStack() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop())
# coding:utf-8 import threading from werkzeug.local import LocalStack def worker(): print('new thread..') print(threading.current_thread().getName()) if __name__ == '__main__': # print('hello') # t = threading.current_thread() # print(t.getName()) # MainThread # th1 = threading.Thread(target=worker, name='my Thread') # th1.start() s = LocalStack() s.push(20) print(s.top) s.push(30) print(s.pop()) print(s.top) print('123' or 'hello')
from werkzeug.local import LocalStack import threading import time my_stack = LocalStack() my_stack.push(2) print('in main thread after push,value is: ' + str(my_stack.top)) def worker(): print('in new thread before push, value is: ' + str(my_stack.top)) my_stack.push(1) print('in new thread after push, value is: ' + str(my_stack.top)) new_t = threading.Thread(target=worker, name='qiyue_thread') new_t.start() time.sleep(1) print('finally , in main thread value is: ' + str(my_stack.top))
class wsgiApp: __config = None logger = None def __init__(self): self.__url_map = Map([ Rule('/', endpoint='hello') # Rule('/<short_id>', endpoint='follow_short_link'), # Rule('/<short_id>+', endpoint='short_link_details') ]) self.logger = loadLogging(self.logger) self.is_run = False self.__view_functions = dict() self.__localstack = LocalStack() self.__read_config() def __read_config(self): if self.__config is None: configp = ConfigParser(allow_no_value=True) dirlist = os.listdir(os.getcwd() + '\\config') config_files = list() for dirname in dirlist: if dirname.endswith('.ini'): config_files.append(dirname) self.__config = dict() for config_file in config_files: configp.read(os.getcwd() + '\\config\\' + config_file) sections = configp.sections() for section in sections: item = dict() for key, value in configp.items(section): item[key] = value self.__config[section] = item def get_config(self): if self.__config is None: self.__read_config() return self.__config def run(self): if self.is_run is True: print 'the app is already running' else: config = self.get_config() run_simple(hostname=config['BaseConfig']['hostname'], port=int(config['BaseConfig']['port']), application=self) self.is_run = True def get_data(self, request): if request.method.lower() == 'post': data = request.form.to_dict() else: data = request.args.to_dict() writeLogging(self.logger, 'get request:' + str(data)) return data def get_local_attr(self, attr): local_attr = LocalProxy(self.__localstack.top[attr]) return local_attr def get_request(self): return self.get_local_attr('request') def __push_local_attr(self, local_attr): def get_it(): return local_attr return get_it def __call__(self, environ, start_response): request = Request(environ) self.__localstack.push({"request": self.__push_local_attr(request)}) adapter = self.__url_map.bind_to_environ(request.environ) try: endpoint, values = adapter.match() status = 200 if endpoint in self.__view_functions: res = self.__view_functions[endpoint]() else: res = getattr(self, 'on_' + endpoint)(request) except NotFound, e: status = 404 res = e.get_body() except MethodNotAllowed, e: status = 405 res = e.get_body()
#-*- coding:utf-8 _*- """ @author:star @file: test7.py @time: 2018/08/12 """ from werkzeug.local import LocalStack, LocalProxy user_stack = LocalStack() user_stack.push({'name': 'alice'}) user_stack.push({'name': 'bob'}) def get_user(): return user_stack.pop() user = LocalProxy(get_user) print(user.get('name')) print(user.get('name'))
from werkzeug.local import Local, LocalStack, LocalProxy ls = LocalStack() ls.push(42) print(ls.top) ls.push(23) print(ls.top) print(ls.pop()) print(ls.top)
from werkzeug.local import LocalStack, LocalProxy test_stack = LocalStack() test_stack.push({"abc": "123"}) test_stack.push({"abc": "1234"}) def get_item(): return test_stack.pop() # LocalProxy 需要初始化callable的对象,然后每次调用proxy时 内部会去call一次这个初始化对象。 item = LocalProxy(get_item) print(item["abc"]) print(item["abc"])
class LoggingMiddleware(object): def __init__(self, app, auto_install=True): self.app = app self.context = LocalStack() if auto_install: logger = getLogger() logger.setLevel(DEBUG) logger.addHandler(self.handler) @cached_property def handler(self): return WSGIHandler(self) def __call__(self, environ, start_response): html = [False] def start(status, headers, exc_info=None): headers = list(headers) replaced_headers = [] for k, v in headers: name = k.lower().strip() if name == 'content-type': content_type = v.lower().split(';')[0] content_type = content_type.strip().lower() html[0] = content_type == 'text/html' if name != 'content-length': replaced_headers.append((k, v)) return start_response(status, replaced_headers) self.context.push([]) result = self.app(environ, start) result = list(result) if html[0]: return self.inject_log_html(result) return result def inject_log_html(self, iterable): injected = False for chunk in iterable: if not injected and '</body>' in chunk: a, b = chunk.split('</body>', 1) yield a for subchunk in self.log_html(): yield subchunk yield b injected = True else: yield chunk if not injected: for chunk in self.log_html(): yield chunk def log_html(self): level_map = {DEBUG: 'debug', INFO: 'info', WARNING: 'warn', ERROR: 'error', CRITICAL: 'error'} records = self.context.pop() yield '<script>\n//<![CDATA[\nif (console) {\n' for record in records: yield 'console.' yield level_map[record.levelno] yield '(' yield dumps(record.name) yield ' + ": " + ' yield dumps(str(record.getMessage())) yield ');' yield '\n}\n// ]]>\n</script>'
# webserver的概念 java php nginx apache tomcat iis # app.run()使用的是单进程, 单线程处理请求 #Local: 使用字典的方式实现的线程隔离 #LocalStack: 封装了Local, 实现了线程隔离的栈 """ from werkzeug.local import Local from threading import Thread import time my_obj = Local() my_obj.b = 1 def worker(): my_obj.b = 2 print("in new thread b is ", my_obj.b) new_t = Thread(target=worker) new_t.start() time.sleep(1) print("in main thread b is ", my_obj.b) """ from werkzeug.local import LocalStack s = LocalStack() s.push(1) print(s.top)
# -*- coding: UTF-8 -*- """ @author: Frank @contact: [email protected] @file: test6.py @time: 2018/11/3 上午10:05 """ import threading import time from werkzeug.local import LocalStack local_stack = LocalStack() local_stack.push(1) print(f'in the Main thread after push, local_stack.top: {local_stack.top}') def worker(): print(f'in the worker,before push . local_stack.top: {local_stack.top}') local_stack.push('frank') print(f'in the worker, after push . local_stack.top: {local_stack.top}') work_thread = threading.Thread(target=worker, name='work_thread') work_thread.start()
def manipulate(): obj.a = 2 print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a) newThread = Thread(name='newThread', target=manipulate) newThread.start() time.sleep(1) print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a) # 线程隔离栈的试验 stk = LocalStack() stk.push(1) print(f'In {current_thread().name} {stk._local.__ident_func__()} stk.top is', stk.top) def manipulateStack(): print( f'In {current_thread().name} {stk._local.__ident_func__()} stk.top is', stk.top) newTread2 = Thread(name='newThread2', target=manipulateStack) newTread2.start() time.sleep(1) print(f'In {current_thread().name} {stk._local.__ident_func__()} stk.top is',
from werkzeug.local import LocalStack # 要创建一个栈对象, 要实现push, pop, top方法 # 1. 实例化LocalStack s = LocalStack() s.push(1) # 压栈 print(s.top) # 取栈顶, top不是方法是属性, 调用的时候不需要括号 print(s.top) # 栈顶元素不会被删除 print(s.pop()) # 弹出栈顶元素 print(s.top) # 元素已经被删除 s.push(1) s.push(2) print(s.top) print(s.top) # 两次取的都是同一个元素 s.pop() # 后进先出 print(s.top)
# LocalStack Test file import threading import time from werkzeug.local import LocalStack ls = LocalStack() # 主线程中对ls栈中推入元素 ls.push(1) def worker(): # 新的线程中,将会创建一个新栈与主线程隔离互不影响,这里刚创建的栈所以为空 print("新线程中取栈顶元素", ls.top) ls.push(2) print("推入元素后在查看栈顶元素", ls.top) new_thread = threading.Thread(target=worker, name="newThread") new_thread.start() time.sleep(1) print("此时主线程中栈顶元素", ls.top)
# @Time : 2020/2/20 15:46 # @Author : tongyue import threading from werkzeug.local import LocalStack myStack = LocalStack() myStack.push(1) print("主线程myStack.top:{}".format(myStack.top)) def workerA(): myStack.push(2) print("线程1 myStack.top:{}".format(myStack.top)) def workerB(): myStack.push(3) print("线程2 myStack.top:{}".format(myStack.top)) #子线程 trA = threading.Thread(target=workerA) trB = threading.Thread(target=workerB) trA.start() trB.start() ''' myStack同一个对象各个线程的栈互不干扰 '''
# # ls = LocalStack() # ls.push(1) # # # def worker1(): # """线程1""" # print('线程1中的栈顶的值为:{}'.format(ls.top)) # ls.push(2) # print('线程1中的栈顶的值为:{}'.format(ls.top)) # # # t1 = threading.Thread(target=worker1, name='线程1') # t1.start() # t1.join() # print('主线程中的栈顶的值为:{}'.format(ls.top)) from werkzeug.local import LocalStack, LocalProxy user_stack = LocalStack() user_stack.push({'name': 'Bob'}) user_stack.push({'name': 'John'}) def get_user(): return user_stack.pop() # 使用 LocalProxy user = LocalProxy(get_user) print(user['name']) print(user['name'])
from werkzeug.local import LocalStack import threading import time # push pop top my_stack=LocalStack() my_stack.push(1) print('in main thread after push ,value is :'+str(my_stack.top)) def worker(): print('in new thread befor push ,value is:'+str(my_stack.top)) my_stack.push(3) print('in new thread after push ,value is :'+str(my_stack.top)) new_t=threading.Thread(target=worker(),name='qiyue_thread') new_t.start() time.sleep(1) print('finally,in main thread values is : '+str(my_stack.top))
#!/usr/bin/env python # -*- coding: utf-8 -*- # Date: '2020/02/14 15:52' import threading import time from werkzeug.local import Local, LocalStack t = LocalStack() t.push(1) def func(): print("func :", t.top) t.push(2) print("func ...", t.top) nt = threading.Thread(target=func) nt.start() time.sleep(1) print("main threading", t.top)
Created by ZZXUN on 2018/8/6 """ import threading import time from werkzeug.local import Local, LocalStack __author__ = "ZZXUN" class A: b = 1 my_job = LocalStack() my_job.push(1) # 两个线程实例化两个栈,彼此数据不干扰 def worker(): print("in new thread before push, value is :" + str(my_job.top)) my_job.push(2) print("in new thread after push, value is :" + str(my_job.top)) new_t = threading.Thread(target=worker, name="zzx") new_t.start() time.sleep(1) print("in main thread before push, value is :" + str(my_job.top))
# coding:utf-8 import threading import time from werkzeug.local import Local, LocalStack class A(object): a = 100 obj = Local() obj.a = 1 s = LocalStack() s.push(100) def fun(): obj.a = 20 print('in new thread obj.a ia', obj.a) print(s.top) s.push('new word') print(s.top) if __name__ == '__main__': t = threading.Thread(target=fun, name='mythread') t.start() time.sleep(1) print('in main thread obj.a is', obj.a)
# def __setattr__(self, key, value): # # self.__storage__[key] = value # pass # def query(self): # return self.__storage__ # # local = Local() # local.__storage__['hah'] = 1 # print(local.query()) # print(local.hah) from werkzeug.local import LocalStack import threading import time stack = LocalStack() stack.push(1) print('main thread value is {}'.format(stack.top)) def work(): print('{} value is {}'.format(threading.current_thread().name, stack.top)) stack.push(2) print('{} value is {}'.format(threading.current_thread().name, stack.top)) if __name__ == '__main__': t = threading.Thread(target=work, name='lee') t.start() time.sleep(1) print('main thread value is {}'.format(stack.top))
from werkzeug.local import LocalStack import threading import time my_obj = LocalStack() my_obj.push(1) def worker(): print('in new thread before push, top is: ' + str(my_obj.top)) my_obj.push(2) print('in new thread after push, top is: ' + str(my_obj.top)) new_t = threading.Thread(target=worker, name='new') new_t.start() time.sleep(1) print('in main thread the top is :' + str(my_obj.top)) ########################## None 2 1
class NullTranslationContext(TranslationContextBase): def __init__(self): TranslationContextBase.__init__(self) self.translations = NullTranslations() self.lang = 'sk' class TranslationContext(TranslationContextBase): def __init__(self, locale): TranslationContextBase.__init__(self) self.lang = locale self.translations = support.Translations.load(os.path.join(current_app.root_path, 'translations'), [locale]) _translation_stack.push(NullTranslationContext()) def _get_context(): v = _translation_stack.top if v is None: return NullTranslationContext() return v current_trans = LocalProxy(_get_context) def _(msg): v = current_trans.translations.gettext(msg) if not isinstance(v, unicode): v = v.decode('utf-8') return v
# _*_ coding:utf-8 _*_ __author__ = 'Xbc' from werkzeug.local import LocalStack s = LocalStack() # push pop top s.push(1) # 添加 print(s.top) # 取 print(s.top) # 取 print(s.pop()) # 删除 print(s.top) # 取 # 1 # 1 # 1 # None s.push(1) print(s.top) s.push(2) # 栈 后进先出 print(s.top) print(s.top) print(s.pop()) print(s.top) # s[7] 栈 序列(列表) # 数据结构 限制了某些能力
# -*- coding: utf-8 -*- """ Created by Cphayim at 2018/6/27 23:20 """ import threading import time from werkzeug.local import LocalStack __author__ = 'Cphayim' my_stack = LocalStack() my_stack.push(1) print('in main thread after push, value is: ' + str(my_stack.top)) def worker(): # 新线程 print('in new thread before push, value is: ' + str(my_stack.top)) my_stack.push(2) print('in new thread after push, value is: ' + str(my_stack.top)) new_t = threading.Thread(target=worker, name='q') new_t.start() time.sleep(1) # 主线程 print('finally, in main thread value is: ' + str(my_stack.top))
""" @author: MH @contact: [email protected] @file: test2.py @time: 2018/7/24 10:31 LocalStack<线程隔离栈> """ from werkzeug.local import LocalStack # 实例化县城隔离栈 s = LocalStack() # 将想要隔离的对象推入到栈中 s.push('dm') # 取栈顶元素 print(s.top) # top方法并不会清除掉栈内元素 print(s.top) # 出栈,释放资源(释放栈顶元素) s.pop() # 出栈以后栈内资源被释放,所以栈顶元素为空 print(s.top)
from werkzeug.local import LocalStack l = LocalStack() l.push(42) l.push(23) l.pop()
以线程ID号作为key的字典->Local->LocalStack 使用线程隔离的意义: 使当前线程能够正确引用到他自己所创建的对象,而不引用到其他线程所创建的对象 flask中request、sesion、g是线程隔离的对象 ''' import threading import time from werkzeug.local import LocalStack '''---栈基本知识---''' s = LocalStack() s.push(1) #向栈顶推入1 print(s.top) print(s.top) print(s.pop()) print(s.top) # s.top#取出栈顶元素,不会删除栈顶元素 # s.pop()#取出栈顶元素,并删除栈顶元素 s.push(1) s.push(2) print(s.top) print(s.top) print(s.pop()) print(s.top) '''----------------''' '''使用LocalStack,实现线程隔离''' mystack = LocalStack()