Search code examples
pythondjangodjango-channels

Redis and channels with Windows


I'm trying to get a var to my consumers.py to send data to the client in real time as a function does API calls and returns that to the browser.

I know channels needs Redis to function, but why? Why can we not just pass a list as it's built to the consumers class or any variable for that matter? From another answer: to store the necessary information required for different instances of consumers to communicate with one another. But what if I only will use one websocket connection, and only one user is allowed to be logged in at a time? This will be locally hosted only and the function is outside of consumers.py that returns the data so subscribing to groups may be where I need these.

Am I missing something or is redis / memurai a must here? I just can't help but to feel there's an easier way.


Solution

  • I ended up using server side events (SSE), specifically django-eventstream, and so far it's worked great as I didn't need the client to interact with the server, for a chat application this would not work.

    Eventstream creates an endpoint at /events/ the client can connect to and receive a streaming http response.

    Sending data from externalFunc.py:

    send_event('test', 'message', {'text': 'Hello World'})
    

    Event listener in HTML page:

    var es = new ReconnectingEventSource('/events/');
    
    es.addEventListener('message', function (e) {
        console.log(e.data);
    
        var source = new EventSource("/events/")
    
        var para = document.createElement("P");
        const obj = JSON.parse(event.data)
        para.innerText = obj.text;
        document.body.appendChild(para)
    
    }, false);
    
    es.addEventListener('stream-reset', function (e) {
    }, false);