我按照本教程在flask(python3)中设置了一个聊天服务器,它将聊天历史存储在mysql数据库中:https://www.youtube.com/watch?v=pigpdsobnmc
我为main.py提供了以下内容:
from flask import Flask, render_template
from flask_socketio import SocketIO, send
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root@127.0.0.1/chat_db'
db = SQLAlchemy(app)
class History(db.Model): # Call 'History' table from 'chat_db' database
id = db.Column('id', db.Integer, primary_key=True) # Define 'id' column
name = db.Column('name', db.String(500)) # Define 'name' column
message = db.Column('message', db.String(500)) # Define 'message' column
@socketio.on('message')
def handleMessage(name, msg): # Pass 'name' & 'msg' from the socket
print('Message: ' + msg) # Print the message to terminal
message = History(name=name, message=msg) # create 'message' variable where 'message'...
# ...in 'message=msg' is the 'message' column in the 'History' table...
# ...and the 'msg' in 'message=msg' is the passed-in 'msg' variable from the socket.
db.session.add(message) # Add 'message' from the client...
db.session.commit() # ... and commit (save) the message to the database.
send(command(name, msg), broadcast=True) # Broadcast the message (display on the web page)
def command(name, msg):
send_back = ""
if (msg == "/load-history"):
send_back = "Command recognized"
else:
send_back = "<b>"+name+"</b>"+': '+msg # Broadcast the message (display on the web page))
return send_back
@app.route('/')
def index():
messages = History.query.all() # Query all rows from chat 'History' table
return render_template('index.html', messages=messages)
if __name__ == '__main__':
socketio.run(app)
对于templates/index.html,请执行以下操作:
<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('message', function(msg) {
$("#messages").append('<li>'+msg+'</li>');
console.log('Received message');
});
$('#sendbutton').on('click', function() {
socket.send($('#myName').val(), $('#myMessage').val());
$('#myMessage').val('');
});
});
</script>
<ul id="messages" style="list-style: none;">
{% for msg in messages %}
<li>{{ ': '+msg.message }}</li>
{% endfor %}
</ul>
<input type="text" id="myName" placeholder="Username">
<input type="text" id="myMessage" placeholder="Message">
<button id="sendbutton">Send</button>
</body>
</html>
看起来是这样的:
现在,整个 History
聊天历史记录表从main.py的以下部分加载到页面加载:
@app.route('/')
def index():
messages = History.query.all() # Query all rows from chat 'History' table
return render_template('index.html', messages=messages)
我怎样才能更改代码使命令 /load-history
必须在“消息”文本框中输入才能显示聊天历史,而不是在页面加载时全部显示?
1条答案
按热度按时间bpzcxfmw1#
您的消息包含“name:message”
因此,您正在测试消息是否为/load history,但事实上,您的消息总是以“**name:*”作为前缀
这是因为您发送的消息类似于在js中使用socketio:
您应该在两个不同的变量中发送消息和名称,并修改python代码以接受此消息
以及js: