FastApi stuck at Waiting for background tasks to complete. (CTRL+C to force quit)

353 Views Asked by At

Hey guys I am learning reddis with FastApi and created an webscoket endpoint which publish all events which another endpoint recieve.

This is the endpoint to send event message to reddis.

    @app.post("/send_message/{user_id}")
async def sendMessage(user_id:str, message:str):
    if user_id and message:
        await publish_event(f"channel_{user_id}", message)
        return {"message": "Message sent successfully"}

and there is another websocket endpoint which recives event from reddis and send it to user.

    @app.websocket("/ws/{user_id}")
async def websocket_endpoint(websocket:WebSocket, user_id:str):
    # await websocket.accept()
    await manager.connect(websocket)
    channel_name = f"channel_{user_id}"
    async with redis.pubsub() as pubsub:
        await pubsub.subscribe(channel_name)
        try:
            while True:
                message = await pubsub.get_message()
                if message and message["type"] == "message":
                    decoded_message = message["data"].decode("utf-8")
                    # await websocket.send_text(decoded_message)
                    await manager.send_personal_message(decoded_message, websocket)
        except WebSocketDisconnect:
            manager.disconnect(websocket)
            pubsub.unsubscribe(channel_name)

and this is working completely fine but, when I try to exit the server, I get an warning saying Waiting for background tasks to complete. (CTRL+C to force quit) and when I press ctrl +c to forcefully quite the server than I get this.

Traceback (most recent call last):
  File "/Users/nehat/Desktop/google_ai/venv/lib/python3.10/site-packages/starlette/routing.py", line 686, in lifespan
    await receive()
  File "/Users/nehat/Desktop/google_ai/venv/lib/python3.10/site-packages/uvicorn/lifespan/on.py", line 137, in receive
    return await self.receive_queue.get()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/queues.py", line 159, in get
    await getter
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

How should I fix this. please help

0

There are 0 best solutions below