tornado - 异步上下文管理(StackContext)
初步使用
1 | # -*- coding: utf-8 -*- |
异常没有在 main 中捕获:
run async task 1
end
run callback
ERROR:root:Exception in callback <function null_wrapper at 0x7f23ec300488>
Traceback (most recent call last):
File "~/learn/tornado/tornado/ioloop.py", line 370, in _run_callback
包裹上下文
使用 partial 生成新的函数, 最终调用的函数为 wrapper(callback),在 wrapper 中捕获异常
1 | # -*- coding: utf-8 -*- |
异常被正确捕获:
run async task 1
end
run callback
main exception except in callback
使用 tornado stack_context 例子
1 | # -*- coding: utf-8 -*- |
tornado.stack_context.StackContext
tornado.stack_context 相当于一个上下文包裹器,它接收一个 context_factory 作为参数并保存
context_factory 是一个上下文类,拥有 __enter__
__exit__
方法
使用 with stack_context 时候,执行自己的 __enter__
__enter__
函数根据保存的 context_factory 创建一个 context 对象,并执行对象的 __enter__
方法
StackContext 将 (StackContext, context_factory) 保存,将来执行回调的时候再创建一个 StackContext(context_factory) 来执行 call_back
1 | class StackContext(object): |
IOLoop.add_callback
1 | def add_callback(self, callback): |
IOLoop.start
1 | def start(self): |
IOLoop._run_callback
1 | def _run_callback(self, callback): |
stack_context.wrap
1 | def wrap(fn): |
1 | class _StackContextWrapper(functools.partial): |
Sync From: https://github.com/TheBigFish/blog/issues/1