How to create a progress bar using flask?

亡梦爱人 提交于 2021-02-07 08:00:32

问题


Just want to insert a progress bar in my html page. It should load from a for in my app.py. That's what I did so far...

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)

I'm using a bootstrap progress-bar from w3schools in my code

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>

Any help, please?


回答1:


this is pretty simple: poll your api and update the progress bar width and valuenow until finished:

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
     });
}


来源:https://stackoverflow.com/questions/37531829/how-to-create-a-progress-bar-using-flask

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