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?
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.
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.
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.
The Request, in Flask, is an object that contains all the data sent from the Client to Server.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With