gpt4 book ai didi

django - 如何从 django View 向消费者(django-channels)发送消息?

转载 作者:行者123 更新时间:2023-12-04 13:16:26 25 4
gpt4 key购买 nike

我想从 Django View 向 django channel 消费者发送一些消息。我有消费者喜欢:

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class KafkaConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_group_name = 'kafka'

# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)

await self.accept()

async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']

# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'kafka_message',
'message': message
}
)

# Receive message from room group
async def kafka_message(self, event):
message = event['message']

# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))

而且,我的 Django View 是这样的:
from django.views.generic import TemplateView
from django.http import HttpResponse

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


class LogView(TemplateView):
template_name = "kafka/index.html"


def testview(request):
channel_layer = get_channel_layer()

async_to_sync(channel_layer.group_send(
'kafka',
{
'type': 'kafka.message',
'message': 'Test message'
}
))
return HttpResponse('<p>Done</p>')

URL url 是这样的:
from django.urls import path
from .views import LogView, testview

urlpatterns = [
path(r'', LogView.as_view()),
path(r'test/', testview),

]

所以,当我这样做时 http://mydevhost/test/ ,消费者收不到消息。但是,我可以从/在消费者内部发送消息,即 KafkaConsumer.receive在 channel 消费者。

最佳答案

async_to_sync 上犯了很多愚蠢的错误.其实async_to_sync应该只包装 channel_layer.group_send而不是整个,即 async_to_sync(channel_layer.group_send) .所以调用看起来像:

async_to_sync(channel_layer.group_send)(
'kafka',
{
'type': 'kafka.message',
'message': 'Test message'
}
)

所有带有更正代码的查看代码:
from django.views.generic import TemplateView
from django.http import HttpResponse

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


class LogView(TemplateView):
template_name = "kafka/index.html"


def testview(request):
channel_layer = get_channel_layer()

async_to_sync(channel_layer.group_send)(
'kafka',
{
'type': 'kafka.message',
'message': 'Test message'
}
)
return HttpResponse('<p>Done</p>')

关于django - 如何从 django View 向消费者(django-channels)发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59943869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com