【发布时间】:2020-05-24 23:31:07
【问题描述】:
我正在尝试制作一个一对一的聊天应用程序,但是当我向它发送数据时,我的聊天套接字立即断开连接。我认为问题出在我的消费者的异步接收功能上? 它没有给我任何错误原因吗?套接字会静默断开
这是接收处理程序
async def receive(self, text_data):
data = json.loads(text_data)
text = data['message']
room_name = data['room_name']
username = data["username"]
only_one_user = False
profile = self.scope["user"].profile
# GET THE ROOM AND THE PROFILE
room_obj = await database_sync_to_async(Room.objects.get)(pk=self.room_name)
other_user = await database_sync_to_async(room_obj.other_user)(profile)
# CREATE AND ADD THE MESSAGE TO THE ROOM
message = Message.objects.create(author=profile,text=text,to=other_user.user.username)
room_obj.messages.add(message)
room_obj.updated = timezone.now()
room_obj.save()
profile = self.scope["user"].profile
clients_connected = await database_sync_to_async(Websocketclient.objects.filter)(room=int(self.room_name))
if clients_connected.count() < 2:
only_one_user = True
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'data': {"text":text,"pk":room_obj.pk,"author":{"username":message.author.user.username,"image":str(message.author.image)},"only_one_user":only_one_user}
}
)
另外,如果我在未来的工作中遇到任何错误,我怎么能知道我的异步代码中到底有什么错误...
【问题讨论】:
-
Message.objects.create 也应该包含在
database_sync_to_async和room_obj.save()中,任何 DB 操作都需要包含在database_sync_to_async中。至于为什么会吞下错误...欢迎使用 async python :) 尝试一下,除了在你的函数体周围,并打印出你得到的异常,以测试错误是这一点。 -
谢谢它的工作。
标签: python django django-channels