Flask + SSE: why is time.sleep () required?

I am creating a flash application that will run background processes (c multiprocessing.Process

) polling a web service for new data, a data queue so that the Server-Sent-Events endpoint can pass it to the client.

Sample code:

#!/usr/bin/env python
from __future__ import print_function
import itertools
import time
from flask import Flask, Response, redirect, request, url_for

from multiprocessing import Process, Queue

def f(q):
    for i, c in enumerate(itertools.cycle('ABCDEFG')):
        time.sleep(1) 
        q.put( c )


app = Flask(__name__)

q = Queue()

@app.route('/')
def index():
    if request.headers.get('accept') == 'text/event-stream':
        def events():
            for i, c in enumerate(itertools.cycle('ABCDEFG')):
                #yield "data: %s \n\n" % (q.get())
                yield "data: %s \n\n" % (c)
                time.sleep(0.01)
        return Response(events(), content_type='text/event-stream')
    return redirect(url_for('static', filename='index.html'))


if __name__ == "__main__":
    p = Process(target=f, args=(q,))
    p.start()

    app.run(host='localhost', debug=True, port=23423)

    p.join()

      

The problem is, in Chrome, if I delete time.delay(0.01)

after yield

, SSE seems to hang (client side).

+3


source to share


2 answers


It takes time.sleep to keep your client from getting overwhelmed with messages. Otherwise, the Python loop will start sending continuous messages as fast as it can loop. Now that you've configured it, the client will receive roughly 100 messages per second (minus a few to process).



+1


source


Why not use a package like Flask-SSE to handle server-dispatched events?



0


source







All Articles