From 974dc35a97ecbadc14dbebad698d7e0029e9c0e2 Mon Sep 17 00:00:00 2001 From: Oleg Agapov Date: Mon, 22 May 2023 13:11:35 +0300 Subject: [PATCH] Add workaround for async broadcast with reload --- w2/server.py | 10 ++++++---- w2/utils/websocket.py | 3 ++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/w2/server.py b/w2/server.py index 9ee44a0..4c68e63 100644 --- a/w2/server.py +++ b/w2/server.py @@ -8,14 +8,16 @@ from w2.utils.websocket import ConnectionManager from w2.utils.response_model import ProcessStatus from w2.utils.database import DB +from contextlib import asynccontextmanager -app = FastAPI() manager = ConnectionManager() -# start an asynchronous task that will keep broadcasting the process status to all the connected clients -broadcast_continuous = Thread(target=asyncio.run, args=(manager.broadcast_all(),)) -broadcast_continuous.start() +@asynccontextmanager +async def lifespan(app: FastAPI): + asyncio.create_task(manager.broadcast_all()) + yield +app = FastAPI(lifespan=lifespan) # The below endpoint is used to create websocket connection @app.websocket("/ws") diff --git a/w2/utils/websocket.py b/w2/utils/websocket.py index d618987..d543541 100644 --- a/w2/utils/websocket.py +++ b/w2/utils/websocket.py @@ -39,7 +39,8 @@ async def broadcast_all(self): processes = self.db.read_all() await connection.send_json(processes) - time.sleep(1) + import asyncio + await asyncio.sleep(1) except Exception as e: print(e)