websocket - 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 断开连接,握手后没有形成连接。对此的任何帮助将不胜感激。
解决方案
推荐阅读
- javascript - 如何查明是否添加了孩子(appendChild)
- jquery - 从 ul 中删除 li
- python - Elasticsearch:创建查询失败:
- c++ - 我可以 std::forward 折叠表达式中的参数吗?
- react-native - 如何使用 react-native-webrtc 连接 2 个设备
- excel - 如何在 24 小时内计算(总结)适当的百分比(不超过 100%)
- java - Jackson-xml 不解析嵌套对象
- json - 嵌套 JSON 的叶子作为 JS 中的完整数据
- c# - 使用 Windows 标识安全地保存用户数据
- c++ - 来自枚举值的 C++ decltype