Django Channels消费者消费1次呼叫两次

问题描述 投票:0回答:1

我正在使用DRF 3.11.0和Channels 2.4.0的组合来实现一个后台,它被托管在Heroku的1个dyno上,并附加了Redis资源。 我的React前端有一个socket,成功地从后端服务器发送接收。

我遇到了一个问题,任何通过套接字发送回前端的消息都会被发送两次。 我已经通过 console.log 前端只ping一次后端。 我可以通过 print() 内的API调用,该函数只是调用了 async_to_sync(channel_layer.group_send) 一次也是。 问题来自于我的消费者--当我使用了 print(self.channel_name) 里面 share_document_via_videocall(),我可以看到,两个实例有不同的 self.channel_name的人被称为(specific.AOQenhTn!fUybdYEsViaPspecific.AOQenhTn!NgtWxuiHtHBw. 好像消费者连接到了两个不同的频道,但我不知道为什么。 当我把 print() 在我 connect() 我只看到它经历了一次连接过程。

我如何确保我只连接到一个通道?

settings.py:

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            #"hosts": [('127.0.0.1', 6379)],
            "hosts": [(REDIS_HOST)],
        },
    },
}

消费者。

import json
from asgiref.sync import async_to_sync
from channels.db import database_sync_to_async

from channels.generic.websocket import AsyncWebsocketConsumer
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser
from .exceptions import ClientError
import datetime
from django.utils import timezone

class HeaderConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print("connecting")

        await self.accept()
        print("starting")
        print(self.channel_name)
        await self.send("request_for_token")


    async def continue_connect(self):
        print("continuing")
        print(self.channel_name)

        await self.get_user_from_token(self.scope['token'])

        await self.channel_layer.group_add(
            "u_%d" % self.user['id'],
            self.channel_name,
        )
        #... more stuff


    async def disconnect(self, code):
        await self.channel_layer.group_discard(
            "u_%d" % self.user['id'],
            self.channel_name,
        )


    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        if 'token' in text_data_json:
            self.scope['token'] = text_data_json['token']
            await self.continue_connect()


    async def share_document_via_videocall(self, event):

        # Send a message down to the client
        print("share_document received")
        print(event)
        print(self.channel_name)
        print(self.user['id'])

        await self.send(text_data=json.dumps(
            {
                "type": event['type'],
                "message": event["message"],
            },
        ))

    @database_sync_to_async
    def get_user_from_token(self, t):
        try:
            print("trying token" + t)
            token = Token.objects.get(key=t)
            self.user = token.user.get_profile.json()
        except Token.DoesNotExist:
            print("failed")
            self.user = AnonymousUser()

REST API调用。

class ShareViaVideoChat(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):
        data = request.data
        recipient_list = data['recipient_list']

        channel_layer = get_channel_layer()
        for u in recipient_list:
            if u['id'] != None:
                print("sending to:")
                print('u_%d' % u['id'])
                async_to_sync(channel_layer.group_send)(
                    'u_%d' % u['id'],
                    {'type': 'share_document_via_videocall',
                     'message': {
                             'document': {'data': {}},
                             'sender': {'name': 'some name'}
                         }
                     }
                )

        return Response()
django redis django-rest-framework django-channels asgi
1个回答
1
投票

关于你获得不同通道名的调用,你确定你的前端没有两次连接到消费者?在浏览器的调试控制台中检查。

© www.soinside.com 2019 - 2024. All rights reserved.