0

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?

lr_optim
  • 299
  • 1
  • 10
  • 30
  • i use redis in fast api without issue. are you sure your socket setup is functional? fastapi has docs for this: https://fastapi.tiangolo.com/advanced/websockets/. if you can post the actual errors you are getting that will be helpful as well. – NoPlaceLike127.0.0.1 Nov 10 '22 at 15:09
  • I use Redis also and excluding this, without issues. The main problem is, I don't know websockets well enough to know how to deal with it. – lr_optim Nov 10 '22 at 15:24
  • 1
    @Chris Yes, at least partially. Thank you. – lr_optim Nov 14 '22 at 09:41

0 Answers0