Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text/event-stream recognised as a download

I'm trying to implement server push in my Flask project following this tutorial.

I've set it all up with no errors, however when I go to the /stream page, Firefox recognizes it as a file and tries to download it. In Safari it just prints out the data sent. I tried adapting the code to a simpler implementation, where a thread just yields some data each second, however it produced the same results.

My goal is for each time a python script reaches a point in a loop, it will update a progress bar on the web interface.

Any help with this would be great. Thanks.

Edit:

app.py

from flask import Flask, render_template, request, Response

app = Flask(__name__)

def event_stream():
    event = "Hello!"
    yield 'data: %s\n\n' % event

@app.route('/stream')
def stream():
    return Response(event_stream(), mimetype="text/event-stream")

if __name__ == "__main__":
    app.debug = True
    app.run(threaded=True)

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
        var source = new EventSource('/stream');
        source.onmessage = function (event) {
             alert(event.data);
        };
    </script>

</head>
<body>

    <p>Stream page</p>

</body>
</html>
like image 862
DJDMorrison Avatar asked Oct 22 '14 18:10

DJDMorrison


People also ask

What is text event stream?

The event stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored.

What is server sent events example?

A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms (e.g. updating a client-side Web SQL Database or IndexedDB object store). If you'll need to send data to a server, XMLHttpRequest is always a friend. SSEs are sent over traditional HTTP.

How server sent events work?

Server-Sent Events is designed to use the JavaScript EventSource API in order to subscribe to a stream of data in any popular browser. Through this interface a client requests a particular URL in order to receive an event stream.


1 Answers

EDIT

I've uploaded my sample application to my Github. Check it out here: https://github.com/djdmorrison/flask-progress-example


I've worked it out, but for anyone else who gets the same problem:

The index.html page never actually loads, as it's never called in app.py. The way to do it is by going to a separate route, /page for example, and then returning send_file('index/html'). This will load the index page, create the EventSource linked to /stream, which will then start the stream method in app.py and yield the correct data.

Example which creates a progress bar by increasing x every 0.2 seconds and displaying it on the webpage:

app.py

@app.route('/page')
def get_page():
    return send_file('templates/progress.html')

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

progress.html

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script>

    var source = new EventSource("/progress");
    source.onmessage = function(event) {
        $('.progress-bar').css('width', event.data+'%').attr('aria-valuenow', event.data);   
    }
    </script>
</head>
<body>
    <div class="progress" style="width: 50%; margin: 50px;">
        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"></div>
    </div>
</body>
</html>
like image 111
DJDMorrison Avatar answered Oct 10 '22 05:10

DJDMorrison