I have a background task that surely sets a global variable, but FastAPI's endpoint is not able to see that change.
It behaves like FastApi is forking my process, taking initial variable values, eventhough as I read it was only async threaded, thus GIL applies (global variables accessible by threads), also I have workers set to one. Also PID is same in task thread and fastapi's endpoint.
from fastapi import FastAPI
from threading import Thread
from time import sleep
app = FastAPI()
globalVar = 0
@app.get("/")
def read_root():
global globalVar
assert globalVar>0 # <----------- FAILS HERE
return {"Hello": globalVar}
def task():
global globalVar
globalVar = 1
print('globalVar set')
if __name__ == '__main__':
Thread(target=task, args=()).start()
sleep(2) # allow thread to set value
import uvicorn
uvicorn.run('fasterror:app', host='127.0.0.1', port=80, reload=True, access_log=True, workers=1)
assert globalVar>0
AssertionError
I am expecting Fastapi endpoint to be able read write global var and share information with background thread.
Based on answer FastAPI: global variable vs module variable it should work.
Update: thread lock on variable access didn't help.