如何在views.py中创建频道客户端?

时间:2020-04-17 10:18:25

标签: python django websocket django-rest-framework django-channels

我正在用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
        }))

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

1 个答案:

答案 0 :(得分: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)