【发布时间】:2020-08-09 00:01:53
【问题描述】:
所以我正在制作一个使用 websockets 的项目,它运行良好。我决定将 websocket 连接包含到另一个页面,所以我决定在我的 routing.py 中添加另一个页面,我还为另一个页面创建了另一个 ChatConsumer,问题是我释放它们是两个不同的连接,怎么能我让我的其他聊天使用者与其他聊天使用者相同,以便此连接成为相同的 websocket 连接?
这是我的 consumer.py:
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
# print(other_user, me)
thread_obj = await self.get_thread(me, other_user)
self.thread_obj = thread_obj
chat_room = f"thread_{thread_obj.id}"
self.chat_room = chat_room
await self.channel_layer.group_add(
chat_room,
self.channel_name
)
await self.send({
"type": "websocket.accept"
})
# await asyncio.sleep(10)
async def websocket_receive(self, event):
# when a message is received from the websocket
print("receive", event)
front_text = event.get('text', None)
if front_text is not None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get('message')
user = self.scope['user']
username = 'default'
if user.is_authenticated:
username = user.username
myResponse = {
'message': msg,
'username': username,
}
await self.create_chat_message(user, msg)
# broadcast the message event to be send
await self.channel_layer.group_send(
self.chat_room,
{
"type": "chat_message",
"text": json.dumps(myResponse)
}
)
async def chat_message(self, event):
# sends the actual message
await self.send({
"type": "websocket.send",
"text": event['text']
})
async def websocket_disconnect(self, event):
# when the socket connects
print("disconnected", event)
@database_sync_to_async
def get_thread(self, user, other_username):
return Thread.objects.get_or_new(user, other_username)[0]
@database_sync_to_async
def create_chat_message(self, me, msg):
thread_obj = self.thread_obj
return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)
也许你会说“你为什么不在路由中使用聊天消费者?”,我不能使用聊天消费者,因为它给出了这个错误
File "./consumers.py" in websocket_connect
other_user = self.scope['url_route']['kwargs']['username']
'username'
感谢您的帮助
【问题讨论】:
-
您可以添加您尝试的导致错误的路由配置吗?使用路由可能会更简单
标签: python django websocket django-channels