channel_layer.group_add()之后redis库中并没有数据
来源:10-15 排错思路讲解与课后作业

李嘉图principal
2020-09-04
def connect(self):
if self.scope['user'].is_anonymous:
# 未登录的用户拒绝连接
self.close()
else:
self.channel_layer.group_add(self.scope['user'].username, self.channel_name)
self.accept()
执行完成后没有报错,前端看到ws连接成功建立,但无法进入后面的receive方法
去redis中也没有看到建立的组,3库中依然是空的,问题会出在哪里呢?
redis配置也是对的
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': ['redis://127.0.0.1:6379/3', ], # channels缓存通道使用Redis 3
},
}
}
view的逻辑能进入没有报错
class MessageSendViewset(viewsets.GenericViewSet,mixins.CreateModelMixin):
def create(self, request, *args, **kwargs):
"""发送消息,AJAX POST请求"""
sender = request.user
recipient_username = request.data['to']
recipient = get_user_model().objects.get(username=recipient_username)
message = request.data['message']
if len(message.strip()) != 0 and sender != recipient:
msg = Message.objects.create(
sender=sender,
recipient=recipient,
message=message
)
channel_layer = get_channel_layer()
payload = {
'type': 'receive',
'message': message,
'sender': sender.username
}
# group_send(group: 所在组-接收者的username, message: 消息内容)
# async_to_sync(channel_layer.group_send)(recipient.username, payload)
channel_layer.group_send(recipient.username, payload)
return HttpResponse({'msg': msg})
return HttpResponse()
请老师指点一下,谢谢
写回答
1回答
-
视图里面为啥注释掉了“async_to_sync”方法呢,其它地方没看出问题来。
只要建立了websocket连接,redis 3库应该是这个样子
022020-09-09
相似问题