gpt4 book ai didi

Django channel 实时聊天保存发送的消息

转载 作者:行者123 更新时间:2023-12-02 19:25:24 24 4
gpt4 key购买 nike

所以我有一个 Django 应用程序,我在其中使用 channel 来实现实时聊天。我的消费者看起来像这样:

导入json从 asgiref.sync 导入 async_to_sync从channels.generic.websocket导入WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)

self.accept()

def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)

# Receive message from WebSocket
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
username = self.scope["user"]
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'user': username.username
}
)

# Receive message from room group
def chat_message(self, event):
message = event['message']
user=event['user']
print(user)
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message,
'user':user
}))

所以我正在寻找一种方法来保存发送的消息(因为目前它们在刷新时丢失)。我创建了一个 Messages 模型,其中包含用于消息文本的 CharField。我想如果我在 chat_message 函数中执行此操作,我可以保存新消息:

new_message=Messages(text=message)
new_nessage.save()

我的问题是,每当用户连接到聊天时,如何预加载最后 10 条消息?

最佳答案

因此,为了做到这一点,我最终在“接收”函数中将消息保存到数据库中(因为如果将其保存在 chat_message 函数中,则会为每个事件用户保存 1 次)。然后,为了预加载消息,每次打开 websocket 时我都会使用 AJAX 调用,以便使用 python 函数获取最近 10 条消息,然后我将消息作为 JsonResponse 传回( https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html 向下滚动到 AJAX 请求本文的一部分,并按此顺序查看signup.html、urls.py 和views.py 文件以供引用)。

关于Django channel 实时聊天保存发送的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62477711/

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