在 fastapi 中与 mongodb(聊天应用程序)一起使用 scoket.io 时,聊天不会保存

问题描述 投票:0回答:1

使用 mongoDB 在 fastapi 中使用 scoket.io 时不会保存聊天记录

**有时消息被保存,但有时却没有,我认为问题是“并发问题”

当我调试这条新消息时,但没有保存在我的数据库中,我也使用了多种技术,但仍然无法解决这个问题**

@sio.event
async def message(sid, data):
    """Send message event"""
    print(f"====data date : {datetime.utcnow()}  ==")
    try:
        if data['room_id'] is None:
            raise ValueError(f"Field 'room_id' must be a string, not {data['room_id']}")

        data['message']['sent'] = True
        if "createdAt" in data['message']:
            data['message']["createdAt"] = str(datetime.utcnow()) 
        else:
            data['message']["createdAt"] = str(datetime.utcnow()) 

        await sio.emit('message', data['message'], room=data['room_id'])
        await ConversationService().saveConversations(data['room_id'], data['message'])
    except Exception as e:
        print("Error:", e)

 async def saveConversations(self, room_id, data):
        """" create chat room """
        # room create for chat
        import time
        try:
            chat_room = await Rooms.get_by_user_room_id(room_id)
            mood = False
            if chat_room:
                if chat_room.mood =="Discreet":
                    mood =True
            if "image" in data:
                upload_images = await self.uploadImagesToS3Bucket(
                    room_id.replace("/","-"), data["image"], mood)
                data["image"] = upload_images
                await UserActivitiesService().average_photos_sent(data["user"]["_id"])

            if "audio" in data:
                upload_audio = await self.uploadAudioToS3Bucket(
                    room_id.replace("/","-"), data["audio"])
                data["audio"] = upload_audio

            chat_conversation = await Conversations.get_by_user_room_id(str(room_id))
            
            if chat_conversation is None:
                create_conversation =  Conversations(
                    room_id=str(room_id),
                    messages=[data]
                    )
                await create_conversation.create()
            
            else:
                chat_conversation.messages.append(data)

                await chat_conversation.save()
            return True
        except Exception as e:
            print("error==>>>>>>>>>>>>>>>>>>>>>>>",e)
python mongodb socket.io fastapi chat
1个回答
0
投票

你能找到解决方案吗?

© www.soinside.com 2019 - 2024. All rights reserved.