What does Thread Local Objects mean in Flask?

I am reading Flask documentation and I am reading this -

One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code, and yet they should not limit you. Because of this, Flask has several design options that some people may find surprising or unorthodox. For example, Flask uses internal local objects, so you do not need to pass objects from function to function in the request in order to stay in streaming mode. This approach is convenient, but requires a valid query context to inject dependencies or when trying to reuse code that uses the value associated with the request. The Flask project is honest in flow locations, does not hide them, and is called in the code and documentation where they are used.

What does it mean? In particular, the following questions -

  • What are local stream objects? How and when are they used and what purpose do they solve?
  • How does the use of local objects associated with the stream provide internal thread safety and how do objects associated with the passage of objects lead to thread insecurity?
  • What is the meaning of the actual request context in this case?
+5
source share
1 answer

A local stream object is an object that is stored in a dedicated structure that is bound to the current stream identifier. If you ask this structure for an object, it will use the current stream identifier to provide you with data unique to the current stream. See threading.local . You can get more details by entering import _threading_local; help(_threading_local) import _threading_local; help(_threading_local) into your interactive Python interpreter.

This means that whenever you use current_app , g or requests , you get a data structure that is safe to use in your stream, without having to worry about locking and other concurrency issues.

In normal operation, Flask processes incoming WSGI requests; for each such request, a request context is created for you; this is represented by g and request objects. If you try to use any of your representations without an incoming request (say, in your tests), the request object will not work and complains that there is no valid request context. Flask provides you with tools to create this context on demand in this case. See the Faking Resources and Context Documentation , as well as the Request Context chapter.

+14
source

Source: https://habr.com/ru/post/1202753/


All Articles