Flask Static Progress Screen

后端 未结 1 1235
清歌不尽
清歌不尽 2020-12-07 06:00

Option 1: No Javascript

I just want to display a static template that says \'please wait...\' while a task is running. Here is a simplified version of the

相关标签:
1条回答
  • 2020-12-07 06:29

    You can stream a response to get a very simple progress report. See the docs on streaming for more information. This example outputs a percent complete while waiting 5 seconds. Rather than sleeping, you would be processing csv or whatever you need to do.

    from flask import Flask, Response
    import time
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        def generate():
            yield 'waiting 5 seconds\n'
    
            for i in range(1, 101):
                time.sleep(0.05)
    
                if i % 10 == 0:
                    yield '{}%\n'.format(i)
    
            yield 'done\n'
    
        return Response(generate(), mimetype='text/plain')
    
    app.run()
    

    This outputs the following over 5 seconds:

    waiting 5 seconds
    10%
    20%
    30%
    40%
    50%
    60%
    70%
    80%
    90%
    100%
    done
    

    This isn't very complex, but it's also just plain text. A much more powerful solution would be to run the task in the background using Celery and poll it's progress using ajax requests.

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