After several attempts and not getting the result, I wonder if it’s even possible to serve websockets via fastapi and keep it open no more and no less
than a fixed time. This is what I have for the websocket code in my api:
@app.websocket("/ws")
@app.websocket("/ws/{topic}")
async def websocket_endpoint(websocket: WebSocket, topic: Optional[str] = None):
_topic = topic if topic else "default"
await app.ws_manager.connect(websocket, topic=_topic)
try:
while True:
data = await websocket.receive_json()
await app.ws_manager.broadcast(data, _topic)
except WebSocketDisconnect:
await app.ws_manager.disconnect(websocket)
except Exception as e:
print(f"{e}")
and this is how I’m currently running the code:
uvicorn.run(
"broadcasting.api:app",
host="0.0.0.0",
port=8000,
ws_ping_interval=5.0,
ws_ping_timeout=None,
timeout_keep_alive=5*60,
)
I was asked to run the server in a way that any websocket connection stay opened for 5 minutes so that’s why (maybe I’m wrong) I set timeout_keep_alive
to 300 seconds. But, when I test it with postman
websocket client, this doesn’t work and satisfy my requirement. Any suggestion on this matter would save me a world. and yes, I’ve read and searched a lot and could figure it out, so thanks in advance