我无法使用烧瓶socketio,似乎当我致电socketio.emit('my event', 'my message')
时它根本不会发出任何事件......
所以这是我的设置:
|
+--/static <-- css/js/etc.
|
+--/templates <- only home.html
|
+--flask_app.py
home.html
只是一个带有这些scritps的简单聊天窗口,它没有任何问题:
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://' + document.domain + ':' + location.port);
$('form').submit(function(){
socket.emit('request', $('#m').val());
$('#m').val('');
return false;
});
socket.on('message', function(message){
$('#messages').append($('<li>').text(message));
console.log('Message received');
});
</script>
我有一个跟踪模型数据变化的函数,并发出一个事件
通知每个人数据已经改变,问题是我打电话时
socketio.emit(...)
没有人收到通知。
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
app = Flask(__name__)
# App configuration
app.config['SECRET_KEY'] = 'somekey!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
socketio = SocketIO(app)
db = SQLAlchemy(app)
# Simple model
class Person(db.Model):
__tablename__ = 'persons'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
@property
def serialize(self):
return {
'id': self.id,
'name': self.name
}
db.create_all()
@app.route('/')
def index():
return render_template('home.html')
# Whenever a user emits 'request' event via javascripts socketio
@socketio.on('request')
def handle_request(message):
emit('message', str(message), broadcast=True)
# Whenever values are changed in Persons table
@event.listens_for(Person, 'after_update')
def receive_after_update(mapper, connection, target):
print(str(target.serialize))
socketio.emit('message', str(target.serialize)) # <------ This doesn't emit any event...
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=8000, debug=True)
有谁知道这是什么问题? 感谢
忘记提及我通过控制台对数据库进行了更改,并打印出print(str(target.serialize))
答案 0 :(得分:2)
首先我必须用
安装redispip install redis
然后我应该改变这一行:
socketio = SocketIO(app)
到此:
socketio = SocketIO(app, message_queue='redis://')
现在从另一个控制台我可以更改数据库中的值,每个人都会看到更改