简体   繁体   中英

Django Channels - Client receives only one message when Group.send() is called in a loop in consumers.py

I have built a Django app which runs automated testing. I collect the inputs from the user, as to what all tests need to be run and when the user clicks on submit button, the tests run for a few hours to a couple of days (depending on the number of tests selected) and once all the tests are completed, the results are showed on a template.

Now the problem is, till all the tests are completed, the user is not updated with the progress. So I decided to use Django Channles to provide live update to the client as and when I have results for individual tests.

With my implementation, I call the Group('user-1').send({'text': i}) method in a for loop. But all I see in the template is only the output of the last Group('user-1').send({'text': i}) operation.

As per my requirement, once Group('user-1').send({'text': i}) is called, the socket.onmessage() function in the section of my template should receive the message and should again wait for messages sent by subsequent Group('user-1').send({'text': i}) calls.

I saw a very similar question here which is already answered, but the solution is not working for me. Please help me identify what needs to corrected in my code, shown below.

consumers.py
------------
@channel_session_user_from_http
def ws_connect(message, **kwargs):
    http_user = message.user
    if not http_user.is_anonymous:
        message.reply_channel.send({'accept': True})
        Group('user-'+str(http_user.id)).add(message.reply_channel)

def ws_message(message):
    for i in my_results_list:
        Group('user-1').send({'text': i})
        sleep(1)

results.html
------------

 <script>
    // Note that the path doesn't matter for routing; any WebSocket
    // connection gets bumped over to WebSocket consumers

    socket = new WebSocket("ws://" + window.location.host + "/task/summary/");

    socket.onopen = function() {
        socket.send("Hello");
    }

    socket.onmessage = function(message) {
        document.getElementById("demo").innerHTML = message.data;
    }

    socket.onmessage()

    // Call onopen directly if socket is already open
    // if (socket.readyState == WebSocket.OPEN) socket.onopen();
</script>

You are calling document.getElementById("demo").innerHTML = message.data; this overwrites the content of demo each time it is called. You want something like:

document.getElementById("demo").innerHTML += message.data or document.getElementById("demo").innerHTML += '<br />' + message.data

If this answer solves your problem please mark it correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM