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

编程入门 行业动态 更新时间:2024-10-25 21:22:39
本文介绍了如何确保立即发送Django Channels消息而没有延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这个想法是在 worker.connect worker上运行一个后台任务。在执行任务时,我想通过通知组将其进度发送给连接的客户端。

The idea is to run a background task on the worker.connect worker. While executing the task, I would like to send its progress to a connected client via the notifications Group.

问题:发送到通知组的消息被延迟到工人的任务已完成。因此:延迟5秒( sleep(5))后,开始和停止这两个消息同时出现在客户端上。我希望消息开始,然后延迟5秒,然后消息停止。知道为什么不是这种情况吗?

The problem: the messages sent to the notifications Group are delayed until the task on the worker is finished. So: both messages 'Start' and 'Stop' appear simultaneously on the client, after a delay of 5 seconds (sleep(5)). I would expect the message 'Start', followed by a 5sec delay, followed by the message 'Stop'. Any idea why this is not the case?

我正在运行以下三个进程:

I have the following three processes running:

  • daphne tests.asgi:channel_layer
  • python manage.py runworker --exclude-channel = worker.connect
  • python manage.py runworker --only-channel = worker.connect
  • daphne tests.asgi:channel_layer
  • python manage.py runworker --exclude-channel=worker.connect
  • python manage.py runworker --only-channel=worker.connect

在 views.py :

def run(request, pk): Channel('worker.connect').send({'pk': pk}) return HttpResponse(status=200)

在 consumers.py :

def ws_connect(message): Group('notifications').add(message.reply_channel) message.reply_channel.send({"accept": True}) def worker_connect(message): run_channel(message)

在 views.py :

def run_channel(message): Group('notifications').send({'text': 'Start'}) sleep(5) Group('notifications').send({'text': 'Stop'})

routing.py

channel_routing = { 'websocket.connect': consumers.ws_connect, 'worker.connect': consumers.worker_connect, }

推荐答案

您可以将 immediately = True 添加为 send 函数的参数。根据消息来源:

You can add immediately=True as argument to the send function. According to the source:

发送被延迟到消费者完成为止。要覆盖它,您可以立即传递= True。

Sends are delayed until consumer completion. To override this, you may pass immediately=True.

github/django/channels/blob/master/channels/channel.py#L32

更多推荐

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

本文发布于:2023-10-28 23:44:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消息   Django   Channels

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!