Flask + RabbitMQ + SocketIO - forwarding messages Flask + RabbitMQ + SocketIO - forwarding messages flask flask

Flask + RabbitMQ + SocketIO - forwarding messages


I had a similar issue, in the end of the day it's because when you make a request flask passes the request context to client. But the solution is NOT to add with app.app_context(). That is hackey and will definitely have errors as you're not natively sending the request context.

My solution was to create a redirect so that the request context is maintained like:

def sendToRedisFeed(eventPerson, type):    eventPerson['type'] = type    requests.get('http://localhost:5012/zmq-redirect', json=eventPerson)

This is my redirect function, so whenever there is an event I'd like to push to my PubSub it goes through this function, which then pushes to that localhost endpoint.

from flask_sse import sseapp.register_blueprint(sse, url_prefix='/stream')@app.route('/zmq-redirect', methods=['GET'])def send_message():    try:        sse.publish(request.get_json(), type='greeting')        return Response('Sent!', mimetype="text/event-stream")    except Exception as e:        print (e)        pass

Now, whenever an event is pushed to my /zmq-redirect endpoint, it is redirected and published via SSE.

And now finally, just to wrap everything up, the client:

var source = new EventSource("/stream");source.addEventListener(  "greeting",  function(event) {    console.log(event)  })


The error message suggests that it's a Flask issue. While handling requests, Flask sets a context, but because you're using threads this context is lost. By the time it's needed, it is no longer available, so Flask gives the "working outside of request context" error.

A common way to resolve this is to provide the context manually. There is a section about this in the documentation: http://flask.pocoo.org/docs/1.0/appcontext/#manually-push-a-context

Your code doesn't show the socketio part. But I wonder if using something like flask-socketio could simplify some stuff... (https://flask-socketio.readthedocs.io/en/latest/). I would open up the RabbitMQ connection in the background (preferably once) and use the emit function to send any updates to connected SocketIO clients.