I have a FastAPI application that needs to send data to the frontend with websockets. The data is received from another application by listening a Redis pubsub channel. I'm totally amateur with websockets and not sure how should I proceed with this task. Here is what I've tried:
I have a function that connects to a Redis channel and listens to it. Is it possible to send data from this function to some websocket endpoint so that frontend could receive them?
from websockets import connect
from app.db.redis import pubsub
async def get_redis_msg():
subscribe = pubsub.pubsub()
subscribe.psubscribe("test_channel")
while True:
msg = subscribe.get_message()
print(f"New message: {msg['data']}")
# Is this possible?
async with connect("ws://localhost:8000/ws") as websocket:
await websocket.send("Hello world!")
Another option I've been trying to do is to use a websocket endpoint like this:
from redis import Redis
from app.db.redis import pubsub
pubsub = Redis()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
ps = pubsub.pubsub()
ps.psubscribe('test_channel')
await websocket.send_text(f"Message text was: {data}")
This one fails because for some reason it can't connect to Redis. Running this as a separate script without websocket and endpoint -stuff runs perfectly and subscribes to the test_channel
. Any ideas how to continue with this?