如何使用Flask创建进度条?

4

我想在我的html页面中插入一个进度条。它应该从我的app.py中的for循环中加载。到目前为止,这是我所做的...

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/progress')
def ajax_index():

   for i in range(500):
      print("%d" % i)
      # I want to load this in a progress bar

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

我在我的代码中使用了来自w3schools的Bootstrap进度条。

index.html

<html>
    <head>
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
       <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
       <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

       <script>
            $(function () { 
                $("#content").load("/progress"); 
            });
       </script>

    </head>
    <body>
        <div class="container">
           <h2>Progress Bar With Label</h2>
           <div class="progress">
              <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:0%"></div>
           </div>
        </div>
    </body>
</html>

有任何帮助吗?


你需要在单独的进程或后台线程中实际执行需要时间的操作,并将其任务进度存储在某个地方,以便/progress可以获取它。你正在展示什么进度? - Alex Hall
1个回答

4
这很简单:轮询您的API并更新进度条宽度和valuenow,直到完成。
var interval = setInterval(update_progress, 1000);
function update_progress() {
     $.get('/progress').done(function(n){
         n = n / 5;  // percent value
         if (n == 100) {
            clearInterval(interval);
            callback(); // user defined
         }
         $('.progress-bar').animate({'width': n +'%'}).attr('aria-valuenow', n);    
     }).fail(function() {
         clearInterval(interval);
         displayerror(); // user defined
     });
}

7
能否提供一个可用的示例?我遇到了同样的问题,但由于我对 jQuery 和 Flask 还比较陌生,所以无法实现这个解决方案。 - AaronDT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接