I’m trying to set up a WebSocket proxy using FastAPI to connect to a Streamlit app, but I’m encountering issues with establishing the WebSocket connection. The Streamlit app is a standard one (not modifiable).
Here’s a simplified version of my FastAPI WebSocket proxy code:
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import websockets
app = FastAPI()
STREAMLIT_APP_URL = "ws://your_streamlit_app_url"
@app.websocket("/{path:path}")
async def websocket_proxy(websocket: WebSocket, path: str):
print(f"Proxying WebSocket connection for path: {path}")
try:
async with websockets.connect(
f"{STREAMLIT_APP_URL}/{path}",
extra_headers=websocket.headers,
open_timeout=10 # Adjust timeout as needed
) as backend_websocket:
while True:
try:
frontend_msg = await websocket.receive_text()
await backend_websocket.send(frontend_msg)
backend_msg = await backend_websocket.recv()
await websocket.send_text(backend_msg)
except WebSocketDisconnect:
break
except Exception as e:
print(f"Error in WebSocket communication: {e}")
break
except websockets.exceptions.WebSocketException as e:
print(f"WebSocket connection error: {e}")
await websocket.close(code=1011)
except Exception as e:
print(f"Error connecting to backend WebSocket: {e}")
await websocket.close(code=1011)
Problem: I’m consistently getting a TimeoutError
or WebSocketException
when attempting to connect to STREAMLIT_APP_URL
. I have verified that the URL is correct and accessible from my server.`
Question: How can I troubleshoot and resolve these WebSocket connection issues between FastAPI and my Streamlit app? Are there specific configurations or best practices I should follow for such WebSocket integrations?
Any insights or suggestions would be greatly appreciated. Thank you!