1

So I'm using Flask_Socket to try to implement a websocket on Flask. Using this I hope to notify all connected clients whenever a piece of data has changed. Here's a simplification of my routes/index.py. The issue that I have is that when a websocket connection is opened, it will stay in the notify_change loop until the socket is closed, and in the meantime, other routes like /users can't be accessed.

from flask_sockets import Sockets
sockets = Sockets(app)

@app.route('/users',methods=['GET'])
def users():
     return json.dumps(get_users())

data = "Some value" # the piece of data to push
is_dirty = False # A flag which is set by the code that changes the data
@sockets.route("/notifyChange")
def notify_change(ws):
    global is_dirty, data
    while not ws.closed:
        if is_dirty:
            is_dirty = False
            ws.send(data)

This seems a normal consequence of what is essentially a while True: however, I've been looking online for a way to get around this while still using flask_sockets and haven't had any luck. I'm running the server on GUnicorn

flask/bin/gunicorn -b '0.0.0.0:8000' -k flask_sockets.worker app:app

I tried adding threads by doing --threads 12 but no luck.

Note: I'm only serving up to 4 users at a time, so scaling is not a requirement, and the solution doesn't need to be ultra-optimized.

Jad S
  • 2,705
  • 6
  • 29
  • 49
  • put in a gevent.sleep() in the while loop to allow gevent to context switch – reptilicus Nov 03 '16 at 16:51
  • I want the loop to be triggered when the flag is changed, instead of on a fixed period basis. Perhaps a gevent equivalent of a threading Event or Condition would be better – Jad S Nov 07 '16 at 15:56

0 Answers0