1

I am trying to create web app where you can click button and it will use data that was just inserted into database to run a script, that runs for few minutes. I want it to be so that onclick it runs python script in background and progressbar would show the progress of the script in %.

Now i have two routes where my progressbar works and script runs seperately. My app splits out output of my script when it is done all at once, so I need to have progressbar that tracks it's progress

Progressbar on website

<div class="progress" style="width: 50%">
    <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
        <span class="progress-bar-label">0%</span>
    </div>
</div>

Javascript

var source = new EventSource("/progress");
source.onmessage = function(event) {
    $('.progress-bar').css('width', event.data+'%').attr('aria-valuenow', event.data);
    $('.progress-bar-label').text(event.data+'%');

    if(event.data == 100){
    source.close()
    }
}

Flask routes

@bp.route('/progress')
def progress():
    def generate():
        x = 0
        while x <= 100:
            yield "data:" + str(x) + "\n\n"
            x = x + 1
            time.sleep(0.5)

    return Response(generate(), mimetype='text/event-stream')

@bp.route('/runscript/', methods=['GET', 'POST'])
def UpdateScript():
    if request.method == 'POST':
        try:
            #Take data from website using form and insert into database
            db.session.add(my_data)
            db.session.commit()
            def inner():
                #Run script that updates stuff using data that was inserted above
                with subprocess.Popen(
                        [sys.executable or 'python', 'C:/Path/To/File/script.py', textwrap.dedent("")],
                        stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        bufsize=1, universal_newlines=True) as p:
                    for line in p.stdout:
                            yield "<code>{}</code>".format(html.escape(line.rstrip("\n")))
                            yield "<br>\n"
            return Response(inner(), mimetype='text/html')
        except Exception as exception:
            print(exception)
            pass

I have tried different methods but i can't seem to get progressbar to track progress of script that is running in background.

Could someone help me please with this? Thanks!

Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
Huikkeli
  • 11
  • 2
  • 3
    Does this answer your question? [Flask App: Update progress bar while function runs](https://stackoverflow.com/questions/24251898/flask-app-update-progress-bar-while-function-runs) – Sergey Shubin Jul 20 '20 at 13:09

0 Answers0