[英]My chat consumer is not working django-channels?
我正在嘗試制作一個一對一的聊天應用程序,但是當我將數據發送給它時,我的聊天套接字立即斷開連接。我認為問題出在我的消費者的異步接收功能中? 它沒有給我任何錯誤的原因? 插座無聲地斷開連接
這是接收處理程序
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 :)
在你的函數體周圍放一個 try except 並打印出你得到的異常來測試錯誤是這個點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.