Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly terminate flask web app running in a thread

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
like image 967
Nazar Avatar asked Mar 24 '18 21:03

Nazar


1 Answers

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 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.

More info is here.

like image 126
Artsiom Praneuski Avatar answered Nov 11 '22 22:11

Artsiom Praneuski