Sending events outside from Flask SocketIO event context

老子叫甜甜 提交于 2019-12-11 07:59:03

问题


When I try to send a socket message outside from the SocketIO event context, the message does not arrive at the client.

Method outside of the context:

@main.route('/import/event', methods=['POST'])
def update_client():
   from .. import socketio
   userid = request.json['userid']
   data = request.json
   current_app.logger.info("New data: {}".format(data))
   current_app.logger.info("Userid: {}".format(userid))
   socketio.emit('import', data, namespace='/events', room=userid)
   return 'ok'

I also tried:

    with current_app.app_context():
        socketio.emit('import', data, namespace='/events', room=userid)

On the SocketIO Context 'on.connect'

@socketio.on('connect', namespace='/events')
def events_connect():
    current_app.logger.info("CONNECT {}".format(request.namespace))
    userid = request.sid
    current_app.clients[userid] = request.namespace

The method update_client will be called from a thread.

On the Client side:

$(document).ready(function(){
  var socket = io.connect('http://' + document.domain + ':' + location.port +'/events');
  var userid;

socket.on('connect', function() {
    console.log("on connect");
});

socket.on('import', function (event) {
  console.log("On import" +event);
});

When I call the emit('import', 'test') in the @socketio.on('connect') method the messages arrives at the client and the log message is printed.

There is an example in the documentation:

@app.route('/ping')
def ping():
    socketio.emit('ping event', {'data': 42}, namespace='/chat')

Do I miss something or why does the message not arrive at the client?

Edit:

The socketio is created in the app/__init__.py function

socketio = SocketIO()
create_app():
   app = Flask(__name__)
   socketio.init_app(app)

manage.py

from app import socketio
if __name__ == '__main__':
    socketio.run(app)

Flask-SocketIO==2.6

eventlet==0.19.0


回答1:


I found a solution.

When I run the application with the flask internal server, the messages are not received by the client.

python manage.py run

But when I run the server with gunicorn all works like a charm.

So the solution here is to use the gunicorn with eventlet.

gunicorn --worker-class eventlet -w 1 manage:app

I use Flask 0.11 with Flask-Migrate 2.0. Perhaps I missed something, since Flask 0.11 has a new startup command.



来源:https://stackoverflow.com/questions/38778315/sending-events-outside-from-flask-socketio-event-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!