kemis
kemis

Reputation: 4604

Refreshing users webpage with python / flask

I am creating a thread and after that thread finishes I want to refresh the users page and send him to another page. But I am really new to python and flask so I have no idea how to do that.

This is my code so far:

nit = Thread()
def stampa():
    print ("Starting")
    com = "python plan.py"
    proc = subprocess.Popen(com.split(),shell=False)
    if proc.wait()!=0:
        print ("Ne radi")
    else:
        print ("Radi")
        return redirect('ended')


@app.route('/', methods=['GET','POST'])
def home():
    return render_template("homepage.html")

@app.route('/start_thread', methods=['GET','POST'])
def start_thread():
    global nit
    nit = Thread(target = stampa)
    nit.start()
    return redirect('end')

@app.route('/end', methods=['GET','POST'])
def end():
    global nit
    if nit.is_alive():
        return "Still working"
    else:
        return redirect('ended')
@app.route('/ended', methods=['GET','POST'])
def ended():
    return "It has ended"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

The homepage template has just 1 button that redirects to start_thread. The reason why I start a thread is because I dont want the windows to freeze while the program runs (it takes about 5 minutes to finish). for now the user has to refresh the page manually to see if the process has finished but I want to be able to do it myself. Does anyone have a solution? ( Or any idea that I can research ?)

Upvotes: 0

Views: 3729

Answers (1)

Tyler
Tyler

Reputation: 674

As stated in the documentation, wait can cause deadlock, so communicate is advisable. subprocess.html#convenience-functions

Please try

def stampa():
    print ("Starting")
    com = "python plan.py"
    proc = subprocess.Popen(com.split(),shell=False)
    if proc.wait()!=0:
        print ("Ne radi")
    else:
        print ("Radi")
        return redirect('ended')

To

def stampa():
    print ("Starting")
    com = "python plan.py"
    proc = subprocess.Popen(com.split(),shell=False)
    stdout, stderr = p.communicate()
    exitCode = proc.returncode
    if (exitCode == 0):
        return redirect('ended') # refresh
    else:
        # raise some exception
        pass

Upvotes: 1

Related Questions