I would like to have a global variable limited to a FastAPI request execution but common to multiple modules. Below is a small example to explain the problem:
I built a very simple app with a main file app.py and a module mymodule. For each test i launch the app in uvicorn with 1 worker and then open 2 python consoles to call for long and short call requests.get("http://localhost:8000/fakelongcall", {"configtest": "long"}), requests.get("http://localhost:8000/fakeshortcall", {"configtest": "short"}).
First situation: it's working but the global variable GLOBAL_VAR is not in a module thus not accessible by an other module (I may be wrong on that).
app.py
import time
from fastapi import FastAPI
GLOBAL_VAR = "default"
app = FastAPI()
@app.get("/fakelongcall")
def fakelongcall(configtest: str):
cpt = 0
while cpt < 10:
print(GLOBAL_VAR)
time.sleep(1)
cpt = cpt + 1
@app.get("/fakeshortcall")
def fakeshortcall(configtest: str):
GLOBAL_VAR = configtest
print("Change done !")
output
INFO: Started server process [34182]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
default
default
Change done !
INFO: 127.0.0.1:52250 - "GET /fakeshortcall?configtest=short HTTP/1.1" 200 OK
default
default
default
default
default
default
default
default
Second situation: both calls are changing the same variable which is not expected but the variable is accessible in a module which is nice.
app.py
import time
from fastapi import FastAPI
import mymodule
app = FastAPI()
@app.get("/fakelongcall")
def fakelongcall(configtest: str):
cpt = 0
while cpt < 10:
print(mymodule.GLOBAL_VAR)
time.sleep(1)
cpt = cpt + 1
@app.get("/fakeshortcall")
def fakeshortcall(configtest: str):
mymodule.GLOBAL_VAR = configtest
print("Change done !")
mymodule.py
GLOBAL_VAR = "default"
output
INFO: Started server process [33994]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
default
default
default
Change done !
INFO: 127.0.0.1:52240 - "GET /fakeshortcall?configtest=short HTTP/1.1" 200 OK
short
short
short
short
short
short
short
Why is this happening ? How can one worker execute 2 calls simultaneously ? What can I do to obtain a module variable that is not shared among different API requests ? Why embedding the same code in a module changes the behavior ?
Thanks in advance for your help.