gevent-socketio send message from thread
Asked Answered
B

1

4

I would like to use gevent-socketio to send messages from a worker thread and update all connected clients on the status of the job.

I tried this:

from flask import Flask, render_template
from flask.ext.socketio import SocketIO, send, emit
import threading
import time

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(message):
    send(message, broadcast=True)

@app.route('/')
def index():
    return render_template('index.html')

def ping_thread():
    while True:
        time.sleep(1)
        print 'Pinging'
        send('ping')

if __name__ == '__main__':
    t = threading.Thread(target=ping_thread)
    t.daemon = True
    t.start()
    socketio.run(app)

And it gives me this error:

RuntimeError: working outside of request context

How do I send messages from a function that doesn't have the @socketio.on() decorator? Can I use gevent directly to send messages to socketio?

Batwing answered 12/11, 2014 at 19:20 Comment(0)
C
2

From this section of the documentation:

Sometimes the server needs to be the originator of a message. This can be useful to send a notification to clients of an event that originated in the server. The socketio.send() and socketio.emit() methods can be used to broadcast to all connected clients:

def some_function():
    socketio.emit('some event', {'data': 42})

This emit is not from from flask.ext.socketio import SocketIO, send, but instead called on your socketio variable from socketio = SocketIO(app). Had you done socketio_connection = SocketIO(app), then you'd be calling socketio_connection.emit() to broadcast your data.

Courbevoie answered 12/11, 2014 at 20:58 Comment(3)
I actually didn't see that section in the documentation (d'oh!). But that is exactly what I tried to do anyway (see my code above) and it doesn't seem to work for me.Batwing
You're calling emit, but the link says to call socketio.emitCourbevoie
Thanks for the feedback, @Celeo. I've updated my post to include more of my code. As you can see, I am importing emit and send directly, not socketio, so that's not my problem.Batwing

© 2022 - 2024 — McMap. All rights reserved.