Django频道。将用户添加到组

时间:2017-10-25 18:40:12

标签: django django-channels

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

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

这是consumers.py应用中的conversations

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中添加一些代码来“订阅”参与者对话更新,如两行:

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

return之前。但是,我不知道如何获取participant_reply_channel的值。

1 个答案:

答案 0 :(得分:1)

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