Properly terminate flask web app running in a thread

前端 未结 1 1327

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 st

相关标签:
1条回答
  • 2021-01-13 15:13

    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.

    0 讨论(0)
提交回复
热议问题