Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

python - What does Thread Local Objects mean in Flask?

I am reading the Flask documentation (specifically, the Foreword for Experienced Programmers chapter) and I read 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 that, Flask has few design choices that some people might find surprising or unorthodox. For example, Flask uses thread-local objects internally so that you don’t have to pass objects around from function to function within a request in order to stay threadsafe. This approach is convenient, but requires a valid request context for dependency injection or when attempting to reuse code which uses a value pegged to the request. The Flask project is honest about thread-locals, does not hide them, and calls out in the code and documentation where they are used.

What does this mean? Specifically the following questions -

  • What are thread local objects? How and when they are used and what purpose do they solve?
  • How using thread-local objects internally ensure thread safety and how does passing objects to function result in not-thread-safe?
  • What is the meaning of a valid request context in this case?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...