A thread-local object is an object that is stored in a dedicated structure, tied to the current thread id. If you ask this structure for the object, it'll use the current thread identifier to give you data unique to the current thread. See threading.local
. You can get more detail still by entering import _threading_local; help(_threading_local)
into your Python interactive interpreter.
This means that whenever you use current_app
, g
or requests
you get a data structure that is safe to use in your thread (or process, or eventlet), without you having to worry about locking and other concurrency issues.
In normal operation, Flask handles incoming WSGI requests; for each such request a request context is created for you; this is represented by the g
and request
objects. If you are trying to use any of your views without an incoming request (say, in your tests), then the request
object will not work and complain that there is no valid request context. Flask provides you with the tools to produce such a context on demand in that case. See the Faking Resources and Context documentation, as well as the Request Context chapter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…