我想从Django视图向django频道消费者发送一些消息。我有这样的消费者:
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视图是这样的:
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。
发布于 2020-01-28 16:40:38
在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>')https://stackoverflow.com/questions/59943869
复制相似问题