我正在使用Python Flask,Flask socket.io和Heroku的PostgreSQL数据库在聊天网站上工作。当消息从Javascript发送到我的Python文件时,我想将该消息存储到数据库中,然后再将消息发送给客户端。 没有存储部分,发出的消息将按预期很快显示。但是,当我在“插入数据库”部分进行编码时,发出的消息至少需要3秒钟才能出现在浏览器中。因此,我认为这是数据库性能的问题。 有没有办法使这个过程更快?我可以以某种方式允许发送该消息并让用户先查看它,然后再进行插入吗?
我正在使用SQLAlchemy ORM作为将消息插入数据库的方式。我尝试使用普通的SQL命令行,但不会产生重大变化。
Python代码(服务器):
@socketio.on("submit message")
def socket_message(data):
user_id = session["user_id"]
rows = User.query.get(user_id)
display_name_user = rows.display_name
now = datetime.datetime.now()
currentDT = now.strftime('%Y-%m-%d %H:%M:%S')
msg = data["msg"]
add_chat = Chat(display_name=display_name_user, messages=msg, time=currentDT)
db.session.add(add_chat)
db.session.commit()
emit("announce message", {"msg": msg, "display_name_user": display_name_user}, broadcast=True)
Javascript:
// Listen to events within the page
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// When connected, start the process to emit the message when input is given
socket.on('connect', () => {
// When the user press Enter in the input box, link this to a button click
document.querySelector('#input-message').addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
event.preventDefault();
// Linking pressing Enter with button being clicked
document.querySelector('#message-button').click();
};
});
// When button is clicked, emit the message
document.querySelector('#message-button').onclick = () => {
const msg = document.getElementById('input-message').value;
socket.emit('submit message', {'msg': msg});
// Clear the input field
document.getElementById('input-message').value = ""
}
});
// When a new message is announced, broadcast it to all computers in the channel
socket.on('announce message', data => {
// Append new message to message list
const header = document.createElement('header')
header.innerHTML = data.display_name_user
const li = document.createElement('li');
li.innerHTML = data.msg;
const hr = document.createElement('hr');
var message_list = document.querySelector('#message-list');
message_list.append(header);
message_list.append(li);
message_list.append(hr);
// Scroll to bottom of page when a new message appears
var message_box = document.querySelector('.message-box');
message_box.scrollTop = message_box.scrollHeight;
});
});
I need the message to be emitted within 1 second maximum.