What does Thread Local Objects mean in Flask?

后端 未结 1 579
暖寄归人
暖寄归人 2020-12-09 16:42

I am reading the Flask documentation and I read this -

One of the design decisions in Flask was that simple tasks should be simple; they should not ta

相关标签:
1条回答
  • 2020-12-09 16:57

    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.

    0 讨论(0)
提交回复
热议问题