Skip to content
Advertisement

Server-Sent Events in Flask work locally but not on production (linode)

I’m trying to get a progress bar to work in Flask. I use a Server Sent Events for that. When I run it in local development server, then everything works well and I can see in the browser real time added numbers in /progress window and progress bar works no problems.

But if I run it in Linux server (Linode), then browser windows hangs for 10 sec and after that progress bar jumps to 100. I am beginner and do not understand why it works in local machine and why not in the remote server. Please somebody explain. And also – which would be a practical solution to this.

Flask – app.py

@app.route('/progress')
def progress():
    def progress_func():
        x = 0
        while x < 100:
            time.sleep(1)
            x = x + 10
            yield 'data:' + str(x) + "nn"
    return Response(progress_func(), mimetype='text/event-stream')

js

var source = new EventSource("/progress");
source.onmessage = function(event) {
    $('.progress-bar').css('width', event.data+'%').attr('aria-valuenow', event.data);
    };

index.html

<div>
    <div class="progress" style="width: 100%; height: 6px;">
    <div class="progress-bar bg-success" role="progressbar" style="width: 6px" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Advertisement

Answer

In my experience that problem can be caused by the reverse proxy between flask and the frontend.

If you use nginx you need to set proxy_buffering to off in order to be able to use SSE

EDIT:

While looking at http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering I noticed that you can achieve the same result by setting the X-Accel-Buffering header to no in the flask response. This solution is better since it’s limited to this specific response.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement