正确终止在线程中运行的Flask Web应用 [英] Properly terminate flask web app running in a thread

查看:494
本文介绍了正确终止在线程中运行的Flask Web应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确终止在单独线程中启动的Flask Web应用程序?我发现不完整的 answer 尚不清楚如何执行此操作.下面的脚本启动了一个线程,该线程又启动了flask应用程序.当我按 CTRL + C 时,某些内容没有终止,并且脚本永不停止.最好在except KeyboardInterrupt:之后添加正确终止appthread_webAPP()的代码.我知道如何终止线程,但是首先我需要终止应用程序:

How to properly terminate a flask web application that was launched in a separate thread? I found an incomplete answer that is not clear on how to do it. The script below starts a thread which in turn starts a flask application. When I press CTRL+C, something is not being terminated and the script never stops. It would be nice to add the code after except KeyboardInterrupt: that terminates the app and the thread_webAPP() properly. I know how to terminate a thread, but first I need to terminate the app:

def thread_webAPP():
    app = Flask(__name__)

    @app.route("/")
    def nothing():
        return "Hello World!"

    app.run(debug=True, use_reloader=False)
    # hope that after app.run() is terminated, it returns here, so this thread could exit


t_webApp = threading.Thread(name='Web App', target=thread_webAPP)
t_webApp.start()

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    print("exiting")
    # Here I need to kill the app.run() along with the thread_webAPP

推荐答案

不要join子线程.使用setDaemon代替:

Dont join child thread. Use setDaemon instead:

from flask import Flask
import time
import threading


def thread_webAPP():
    app = Flask(__name__)

    @app.route("/")
    def nothing():
        return "Hello World!"

    app.run(debug=True, use_reloader=False)


t_webApp = threading.Thread(name='Web App', target=thread_webAPP)
t_webApp.setDaemon(True)
t_webApp.start()

try:
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    print("exiting")
    exit(0)

daemon对于子线程意味着,如果您要停止主线程,则主线程不会等到此守护程序子线程完成其工作.在这种情况下,所有子线程将自动加入,并且主线程将立即成功停止.

daemon for a child thread means that the main thread won't wait till this daemon child thread is finished its job if you're trying to stop the main thread. In this case all child threads will be joined automatically and the main thread will be successfully stopped immediately.

更多信息是此处.

这篇关于正确终止在线程中运行的Flask Web应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆