使用python / flask

时间:2016-12-09 01:16:40

标签: python flask

我正在创建一个线程,在该线程完成后,我想刷新用户页面并将其发送到另一个页面。但我对python和flask真的很新,所以我不知道该怎么做。

到目前为止,这是我的代码:

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)

主页模板只有一个按钮,可重定向到start_thread。 我开始一个主题的原因是因为我不希望在程序运行时窗口冻结(完成大约需要5分钟)。现在,用户必须手动刷新页面以查看该过程是否已完成但我希望能够自己完成。 有没有人有办法解决吗? (或者我可以研究哪些想法?)

1 个答案:

答案 0 :(得分:1)

  

如文档中所述,wait可能导致死锁,因此通信就是   可取。 subprocess.html#convenience-functions

请尝试

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')

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