Django 频道。将用户添加到组

Django Channels. Adding users to a Group

我正在编写一种社交网络应用程序。我想让用户创建对话并在创建对话时将他们的朋友添加到对话中。他们将通过 websocket 接收消息。

我遇到的问题是,我可以在建立 websocket 连接后添加用户以收听他们的对话,但是如何将用户的 reply_channel 添加到某些用户新创建的 Group其他用户对话(而前用户已经建立了 websocket 连接)以便他们可以开始收听来自对话的传入消息?

这是我在 conversations 应用程序中的 consumers.py

from channels import Channel, Group
from channels.sessions import channel_session, enforce_ordering
from channels.auth import channel_session_user, channel_session_user_from_http
from channels.security.websockets import allowed_hosts_only


@allowed_hosts_only
@channel_session_user_from_http
def ws_connect(message):
    user = message.user
    conversation_ids = list(user.conversations.all().values('id'))
    groups = ['_'.join(['conversation', id]) for id in conversation_ids]
    for group in groups:
        Group(group).add(message.reply_channel)
    message.reply_channel.send({"accept": True})

@channel_session_user
def ws_receive(message):
    pass

@channel_session_user
def ws_disconnect(message):
    user = message.user
    conversation_ids = list(user.conversations.all().values('id'))
    groups = ['_'.join(['conversations', id]) for id in conversation_ids]
    for group in groups:
        Group(group).discard(message.reply_channel)
    message.reply_channel.send({"accept": True})

我打算通过 http 请求提交消息。这些是我的 views.py 来自 conversations 应用程序的相关豁免(这是 API 视图,不呈现任何 html)。

class MessageView(APIView):
    permission_classes = (IsAuthenticated,)

    @method_decorator(never_cache)
    def put(self, request):
        user = request.user.id
        conversation_id = request.data.get("conversation_id")
        conversation = get_object_or_404(Conversation, id=conversation_id)
        message_params = {
            request.get('message')
        }
        serializer = MessageSerializer(data=message_params)
        if serializer.is_valid():
            serializer.save()
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

class ConversationView(APIView):
    permission_classes = (IsAuthenticated,)

    @method_decorator(never_cache)
    def put(self, request):
        creator = get_object_or_404(Person, id=request.user.id)
        participants = []
        for participant in request.data.get("participants"):
            participants.append(get_object_or_404(Person, id=participant))
        conversation = create_conversation(creator, *participants)
        serializer = ConversationSerializer(conversation)
        return Response(serializer.data, status=status.HTTP_200_OK)

我想我会在 ConversationView 中添加一些代码到 "subscribe" 参与者的对话更新,如两行:

for participant in participant:
    Group('conversation_'+conversation.id).add(participant_reply_channel)

就在 return 之前。但是,我不知道如何获取 participant_reply_channel.

的值

我最近也在为同样的问题苦苦挣扎。使用 django-channels-presence 解决了我的问题。用户被添加到具有单独组的房间。你想要做的是将用户添加到同一个房间并使用他们由 daphne 生成的原始回复渠道(因此它对每个用户都是唯一的)将解决你的问题。