使用Django Channels作为进度指示器 [英] Using Django Channels for a progress indicator

查看:50
本文介绍了使用Django Channels作为进度指示器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django应用程序,该应用程序在服务器上执行一些计算,这可能需要30秒钟的时间.我正在尝试使用Django渠道创建进度指示器.

I have a django app that carries out some calculations on the server which can take up to 30 seconds. I am trying to use django channels to create a progress indicator.

我的设置基于本教程: https://realpython.com/blog/python/getting-started-with-django-channels/

My setup is based on this tutorial: https://realpython.com/blog/python/getting-started-with-django-channels/

到目前为止,一切都按预期进行.我通过网络套接字提交任务.这是我的使用者收到的,它调用其他方法来完成任务,然后通过websocket返回结果.

Everything is working as expected so far. I submit a task by web socket. This is received by my consumer, which calls other methods to complete the task, then returns the result by websocket.

但是,当我尝试从同一使用者发送多条消息时,所有消息最终都一起到达,而不是在发送时到达.

However, when I try to send multiple messages from the same consumer, all the messages arrive together at the end, rather than arriving when they are sent.

这是我的消费者代码:

@channel_session
def ws_receive(message):
    data = json.loads(message['text'])
    reply_channel = message.reply_channel.name

    Channel(reply_channel).send({
        "text": json.dumps({'progress': 'Starting Work'})
    })      

    # calls outside method to do work
    result = perform_calculations(data, reply_channel)

    Channel(reply_channel).send({
        "text": json.dumps({'progress': 'Finished Work','result':result })
    })  

在此示例中,即使前端之间有30秒的间隔,我的前端也会同时收到开始工作"和完成工作"消息.

In this example, my front end receives the 'Starting Work' and 'Finished Work' messages at the same time, even though there is a 30 second gap between them being generated.

有没有办法使这些消息实时到达?

Is there a way to get these messages to arrive in real time?

推荐答案

是的,您可以使用即时参数.

Yes there is, you could use the immediately parameter.

Channel(message.reply_channel).send({
    "text": json.dumps({'progress': 'Starting Work'})
}, immediately=True)

也在以下位置提到:

如何确保立即发送Django Channels消息而没有延迟?

这篇关于使用Django Channels作为进度指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆