Stack contexts can be used to provide thread-local-like variables, but this is not obvious. We should provide a standard implementation of this pattern or at least document how to build your own.
Notable implementations:
https://gist.github.com/simon-weber/7755289 (discussed on the mailing list)
https://github.com/viewfinderco/viewfinder/blob/master/backend/base/context_local.py
Agree
Tornado has't provider a method like get_current_request() or a global local var
I think is necessary
Doing this sort of thing is definitely not obvious, and its easy to get it wrong. I think both of the implementations that you referenced don't quite fit the bill in various ways. In particular in the viewfinder implementation, when a new StackContext is created (NullContext being the notable example), exit() isn't called on the prior context, so calling ContextLocal.current() will still return the prior set of data even when spawn_callback is used.
After playing with this, I think the real answer is to implement the functionality on top of StackContext instead by implementing a custom stack context. It doesn't require any extra threadlocal objects, piggybacking on the implicit state that is already being managed by tornado.
My implementation (with simplified tests at the bottom) can be found in this gist: https://gist.github.com/virtuald/50bf7cacdc8cfb05e323f350539f0efa
StackContext is deprecated and will be removed in 6.0, so this isn't going to happen (it's also broken for native coroutines). The new contextvars module in Python 3.7 will be the official way to do this in the future.
Most helpful comment
Agree
Tornado has't provider a method like get_current_request() or a global local var
I think is necessary