I'm trying to understand certain concepts in flask and will be grateful to have your suggestions or if you could point me to relevant reference links.
In python, an application by default runs on 1 process and a single thread within that process. If we use threading, then the application starts on 1 process and 1 thread within that process; then, when it encounters the threading code, it will spin up more threads within the same process. While a thread encounters an 'import module' statement, python loads the module in the sys.modules and this happens only once across all threads, even if the code encounters another import with same module name on current thread or any other thread.
However, I am confused about the behaviour in Flask. I have read that one process can have one or more flask applications. And that one flask application be launched in multiple processes.
Also it seems that flask is inherently multi threaded bebecause for example - assuming we have only one flask application, when we run the Flask application, then it gets loaded in say 1 or more processes (each having the main thread) and then for every request made by user, a new thread is assigned to the request. This new thread will process the request (invoke the corresponding function).
I want to know -
1) Considering that flask applications can be loaded in multiple processes and/or each process can have multiple applications, are the modules loaded in the sys.modules per thread (per user) or per process in flask?
2) Suppose a thread updates a global variable or module variable or class variable which is located at the same level as the routes (that is - outside the route function), (I know this is not thread safe, but assume it is updated in such a way that there is no clash). Then, does every subsequent threads (of current user reuqest and other users request) have access to the update made to the global variable or can the subsequent threads only see the original value of the global variable, module var and class var? I am trying to understand if the threads of all users reuqests have access to updates made to the globals because I am under assumption that thread only runs the respective function and nothing else. What is the global variable concept in flask? Is it global for threads across one user or across all users?
I know about the thread local variables (g, current_user) and that they are per request basis. I have also read that normal variables declared in local functions are thread safe but if say I declare variable and point it to an imported module's variable, and then mutate it, then it will update the module variable and any place that references the module variable will see the change. So how is it thread safe?