gpt4 book ai didi

javascript - 整个站点使用一个 Django Channels websocket 消费者?

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:41 26 4
gpt4 key购买 nike

我有一个 Django 项目,它使用 WebSockets 和一个使用者 ( ChatConsumer ) 作为应用程序的聊天和通知部分。

我有routing.py设置为url(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer)然而,由于通知也依赖于 websocket,因此需要从网站上的任何页面访问它们。

原因是当用户点击通知时,它被标记为 read使用

socket.send(JSON.stringify(data));

目前,通知仅在用户使用 /messages/<username>/ 时才有效。网址。

如果我改变routing.py考虑到整个网站(url(r"^", ChatConsumer)),我显然遇到了问题

File "./consumers.py" in websocket_connect
other_user = self.scope['url_route']['kwargs']['username']
'username'

有没有简单的方法可以解决这个问题?因为如果我错了,请纠正我,但我认为编写新的消费者不合适,因为通知和聊天是深深交织在一起的?

消费者.py

class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):

other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
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
# below creates the chatroom
await self.channel_layer.group_add(
chat_room,
self.channel_name
)

await self.send({
"type": "websocket.accept"
})

async def websocket_receive(self, event):
# when a message is recieved from the websocket
print("receive", event)

message_type = json.loads(event.get('text','{}')).get('type')
if message_type == "notification_read":
user = self.scope['user']
username = user.username if user.is_authenticated else 'default'
# Update the notification read status flag in Notification model.
notification = Notification.objects.filter(notification_user=user).update(notification_read=True)
print("notification read")
return

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 = user.username if user.is_authenticated else 'default'
notification_id = 'default'
myResponse = {
'message': msg,
'username': username,
'notification': notification_id,
}
print(myResponse)
await self.create_chat_message(user, msg)
other_user = self.scope['url_route']['kwargs']['username']
other_user = User.objects.get(username=other_user)
await self.create_notification(other_user, msg)

# broadcasts the message event to be sent, the group send layer
# triggers the chat_message function for all of the group (chat_room)
await self.channel_layer.group_send(
self.chat_room,
{
'type': 'chat_message',
'text': json.dumps(myResponse)
}
)

# chat_method is a custom method name that we made
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 disconnects
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)

@database_sync_to_async
def create_notification(self, other_user, msg):
last_chat = ChatMessage.objects.latest('id')
created_notification = Notification.objects.create(notification_user=other_user, notification_chat=last_chat)
return created_notification

base.html

<script>
$(document).ready(function() {
// $('div[id^="notification-"]')
$("#notificationLink").click(function() {
$('span[id^="notification"]').each(function() {
var username = '{{ request.user.username }}'
var data = {
"type": "notification_read",
"username": username,
}
socket.send(JSON.stringify(data));
});
});
</script>

<script>
...
var endpoint = wsStart + loc.host + loc.pathname
var socket = new ReconnectingWebSocket(endpoint)
// all the websocket scripts - client side*
...
</script>

最佳答案

我认为你应该向 other_user 发送消息,所以它应该是这样的

 msg =  loaded_dict_data.get('message')
other_user = loaded_dict_data.get('other_user')

所以你不再需要使用 self.scope['url_route']['kwargs']['username']
顺便说一句,你可以在 github 上分享代码吗,因为我准备做这样的事情,我认为你的项目会对我有很大帮助

关于javascript - 整个站点使用一个 Django Channels websocket 消费者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com