我的聊天消费者无法使用 django-channels?
My chat consumer is not working django-channels?
我正在尝试制作一对一聊天应用程序,但是当我将数据发送到 it.I 时我的聊天套接字立即断开连接 it.I 我认为问题出在我的消费者的异步接收功能中?
它没有给我任何错误原因?套接字静默断开连接
这是接收处理程序
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()
中
简而言之,任何数据库操作都需要包装在 database_sync_to_async
中。
至于为什么错误被吞掉了...欢迎使用async python :)
在你的函数体周围尝试 except 并打印出你得到的异常,以测试错误是否是这一点。
我正在尝试制作一对一聊天应用程序,但是当我将数据发送到 it.I 时我的聊天套接字立即断开连接 it.I 我认为问题出在我的消费者的异步接收功能中? 它没有给我任何错误原因?套接字静默断开连接
这是接收处理程序
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()
简而言之,任何数据库操作都需要包装在 database_sync_to_async
中。
至于为什么错误被吞掉了...欢迎使用async python :)
在你的函数体周围尝试 except 并打印出你得到的异常,以测试错误是否是这一点。