Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Flask keep the request global threadsafe

In flask every function has access to a request global. How do the designers of flask stop that global from being overwritten in the middle of one request when another one starts?

like image 632
lemiant Avatar asked May 18 '14 21:05

lemiant


People also ask

Is Flask request Global?

When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server. Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request.

Are global variables thread-safe in Flask how do I share data between requests?

Global variables are still not thread safe because there's still no protection against most race conditions. You can still have a scenario where one worker gets a value, yields, another modifies it, yields, then the first worker also modifies it.

How do you maintain a state Flask?

You should keep the webserver itself as stateless as possible. Each request should be totally independent and not share any state in the server. Instead, use a database or caching layer which will handle the state for you.

What is the use of request in Flask?

The Request, in Flask, is an object that contains all the data sent from the Client to Server.


1 Answers

It's a threadlocal, not a true global. Since each thread can only be dealing with one request at a time, there's no danger of interference.

In fact there's a full description of exactly this in the Flask docs here.

(Still doesn't necessarily make it a good design, of course.)

like image 175
Daniel Roseman Avatar answered Nov 16 '22 02:11

Daniel Roseman