如何在views.py中成为频道客户端?

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

我正在views.py中创建一个聊天机器人,它将收到用户的HTTP请求,并且views.py与该机器人进行交互并返回给用户。我正在使用通道在views.py和chatbot API之间进行通信。以下是视图代码和频道使用者代码。

#views.py

@api_view(['POST'])
def conv(request):
    ws = create_connection(url)
    ws.send({"message":request.data["msg"]})
    rec = ws.recv()
    return {"msg" : rec}

#consumers.py
class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # 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': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

从通道接收到连接后断开连接,我无法在消费者端维持聊天会话。

python django websocket django-rest-framework django-channels
1个回答
1
投票

我有类似的设置,我认为推送给消费者的代码是错误的。我使用集成到Django频道的功能

以便将一些数据推送到房间中,您可以使用

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(room_group_name, data)
© www.soinside.com 2019 - 2024. All rights reserved.