简体   繁体   English

如何根据flask-socketio中的房间选择显示聊天记录

[英]How to display chat history depending on room selection in flask-socketio

i have some issues here: I'm currently working on a chat application using flask-socketio, everything is actually working fine but i want to add the functionality of allowing users that recently join a room to see the previous chats that were there before they joined, with respect to the room they selected.我这里有一些问题:我目前正在使用flask-socketio开发一个聊天应用程序,实际上一切正常,但我想添加允许最近加入房间的用户查看他们之前的聊天记录的功能加入,关于他们选择的房间。 I'm really stock on figuring out the logic of the functionality.我真的很想弄清楚功能的逻辑。 Below is what i did.下面是我所做的。 The issue is how do i loop through the chats that is being sent to the front-end, or is there a better way of doing it?问题是我如何循环发送到前端的聊天,或者有更好的方法吗?

@socketio.on('join')
def join(data):
    join_room(data['room'])

    room_name = data['room']

    chats = engine.execute(text(
        """SELECT * FROM chat_history WHERE room = :room_name"""), ({"room_name": room_name},)).fetchall()

    if chats:

        send({'msg': data['username'] + " has joined the " + data['room'] + " room."}, room=data['room'], chats=chats)

You need to separate the new user announcement from the chat history, since the announcement goes to everybody in the room, but the chat history only to the user joining.您需要将新用户公告与聊天历史分开,因为该公告会发送给房间中的每个人,而聊天历史只会发送给加入的用户。

You could continue to announce the user with send, but then use emit() with a dedicated event for users joining, where you can include the chat history as an argument:您可以继续使用 send 宣布用户,但随后使用emit()和用户加入的专用事件,您可以在其中将聊天历史记录作为参数:

# announce the new user as before
send({'msg': data['username'] + " has joined the " + data['room'] + " room."}, room=data['room'])

# pass chat history to the new user (note there is no room argument on this one)
emit('joined', chats)

Then in the client you add a handler for the joined event and there you render your chat history.然后在客户端中为joined的事件添加一个处理程序,并在那里呈现您的聊天历史记录。

I hope this makes sense!我希望这是有道理的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM