簡體   English   中英

Django頻道-在consumers.py的循環中調用Group.send()時,客戶端僅收到一條消息

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

我已經構建了運行自動測試的Django應用。 我收集了用戶的輸入,涉及需要運行哪些測試以及當用戶單擊“提交”按鈕時,這些測試運行了幾個小時到幾天(取決於所選測試的數量),一次運行測試完成,結果顯示在模板上。

現在的問題是,在完成所有測試之前,不會向用戶更新進度。 因此,我決定在有單獨測試的結果時使用Django Channles向客戶端提供實時更新。

在實現過程中,我在for循環中調用Group('user-1')。send({'text':i})方法。 但是我在模板中看到的只是最后一個Group('user-1')。send({'text':i})操作的輸出。

根據我的要求,一旦調用Group('user-1')。send({'text':i}),模板部分中的socket.onmessage()函數應接收該消息並再次等待后續Group('user-1')。send({'text':i})調用發送的消息。

我在這里看到了一個非常相似的問題該問題已經得到解答,但是該解決方案對我而言不起作用。 請幫助我確定代碼中需要糾正的內容,如下所示。

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>

您正在調用document.getElementById("demo").innerHTML = message.data; 每次調用它都會覆蓋演示的內容。 您想要類似的東西:

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

如果此答案解決了您的問題,請標記為正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM