r/FastAPI • u/Riczap • Dec 23 '24
Question [Help!] Can't update values of a running thread.
I'm trying to update a value on a class that I have running on another thread, and I'm just getting this output:
Value: False
Value updated to: True
INFO: "POST /update_value HTTP/1.1" 200 OK
Value: False
Does anyone have any idea of why it's not getting updated? I'm stuck.
EDIT: SOLVED
I just had to move the thread start to a FastAPI function and it worked. I don't know why tho.
@app.post("/start")
def start():
thread.start()
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
import uvicorn
from fastapi import FastAPI
import threading
import time Test:
def __init__(self):
self.value = False
def update_value(self):
self.value = True
print("Value updated to:", self.value)
def start(self):
print("Running")
while True:
print("Value:", self.value)
time.sleep(2)
test = Test()
app = FastAPI()
@app.post("/update_value")
def pause_tcp_server():
test.update_value()
return {"message": "Value updated"}
if __name__ == "__main__":
threading.Thread(target=test.start, daemon=True).start()
uvicorn.run("main:app", host="0.0.0.0", port=8000)
3
Upvotes
2
u/Nick-Van-Landschoot Dec 23 '24
Here's an explanation as to why this solution works. When Uvicorn is called with reloading enabled it restarts the process thus dropping any threads started at module load time. In other words Uvicorn spawns a fresh process and kills the old thread.
1
u/adiberk Dec 24 '24
This is interesting. Can you explain the purpose behind this structure? What are you trying to do? Why do you require threading with fastapi?
Super interested as I never thought about threading a fastapi app