text/event-stream recognised as a download

后端 未结 1 490
谎友^
谎友^ 2020-12-01 03:02

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

1条回答
  •  不思量自难忘°
    2020-12-01 04:00

    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

    
    
    
        
        
        
        
    
    
        

    0 讨论(0)
提交回复
热议问题