作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从 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
}))
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>')
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/
我是一名优秀的程序员,十分优秀!