我正在尝试设置一个使用 django2.0.2 和 channels2.1.1 的应用程序。我想要实现的是使用后台/工人任务来执行一些会产生数据的工作,这些数据应该动态地出现在网站上。我的问题主要与渠道有关:我如何正确地在工作人员和连接到 websocket 的消费者之间建立通信?
下面是一个突出问题的最小示例:这个想法是用户触发工作线程,工作线程生成一些数据并通过通道层将其发送到连接到 websocket 的消费者。
#routing.py
from channels.routing import ChannelNameRouter, ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
from testApp.consumers import *
application = ProtocolTypeRouter({
"websocket":AuthMiddlewareStack(
URLRouter([
path("wspath",TestConsumer),
]),
),
"channel":ChannelNameRouter({
"test_worker": TestWorker,
}),
})
Run Code Online (Sandbox Code Playgroud)
消费者:
#consumers.py
from channels.consumer import SyncConsumer
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class TestConsumer(WebsocketConsumer):
def websocket_connect(self,message):
async_to_sync(self.channel_layer.group_add)("testGroup",self.channel_name)
self.connect()
#I understand this next part is a bit weird, but I figured it
#is the most concise way …Run Code Online (Sandbox Code Playgroud)