text/event-stream recognised as a download

℡╲_俬逩灬. 提交于 2019-11-27 18:25:30

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!