首页 > 解决方案 > Websockets 与 asyncio 的连接

问题描述

我正在尝试将 websockets 与 DRF 一起使用。我是 python 中的 asyncio 新手。我正在将 django 通道用于带有 redis 服务器的 websockets。第一次一切正常,但是当我在浏览器中重新加载页面时,握手后 websocket 连接断开。这是我的消费者.py

import json

from channels.generic.websocket import AsyncJsonWebsocketConsumer


class GetPrice(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_group_name = 'notify_price'
        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()
        # print(f"Added {self.channel_name} channel to gossip")

    async def disconnect(self, close_code):
        # Leave room group

        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
        # print(f"Removed {self.channel_name} channel to gossip")

    # Receive message from WebSocket
    async def receive(self, text_data):
        # print('Entered in receive')
        text_data_json = json.loads(text_data)
        message = text_data_json['price']

        # 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):
        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': event['price'],
            'type': 'chat.message',
        }))
        # print(f"Got message {event} at {self.channel_name}")

获取函数在views.py中看起来像这样


    def get(self, request):
        app = App()
        asyncio.set_event_loop(asyncio.new_event_loop())
        asyncio.run(app.run())
        return Response(
            {'message': 'Done},
            status=status.HTTP_200_OK
        )

当我重新加载网页时,websockets 断开连接,握手后没有形成连接。对此的任何帮助将不胜感激。

标签: websocketpython-asynciodjango-channels

解决方案


推荐阅读