正确终止在线程中运行的Flask Web应用程序

9
如何正确终止在单独线程中启动的flask Web应用程序?我发现一个不完整的答案,不清楚如何操作。下面的脚本启动一个线程,该线程又启动了一个flask应用程序。当我按下CTRL+C时,某些内容没有被终止,脚本永远不会停止。希望在except KeyboardInterrupt:之后添加代码,以正确终止appthread_webAPP()。我知道如何终止线程,但首先需要终止应用程序:
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
1个回答

13

不要加入子线程,而是使用setDaemon

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 对于一个子线程来说,意味着主线程不会等待该守护线程完成其工作,即使你试图停止主线程。在这种情况下,所有子线程将会被自动加入并且主线程将立即成功停止。

更多信息请参考此处


还没有尝试过你的建议-会让你知道的。我很惊讶没有人对任何事情发表评论。 - Nazar
@Nazar 当然可以 :) 请把我的帖子当作答案。 - Artsiom Praneuski
exit(0)并没有起到作用。终端没有返回信息,似乎应用程序仍在运行。 - Nazar
你启动了我提供的代码吗?exit(0) 运行得非常好。这是我在按下 Cntrl+C 后得到的输出:https://pastebin.com/TRp3KXKP - Artsiom Praneuski
你是对的。在我添加了t_webApp.setDaemon(True)之后,它正常退出了。我希望它不会留下任何“幽灵”进程。谢谢。 - Nazar
我担心是否需要在Flask线程上进行显式调用stop,以确保线程以干净的方式结束。 - dhalfageme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接