Flask Web server App on Window Python program is not able to shutdown on program exist

Question:

I have python version 3.9, I am using the default development web server that is provided by the flask on windows OS (laptop). I need to run the app on Windows machine, and it should be able to start and stop the app on demand.

Here is what I tried so far. when I run the application either in VS code, I need to force stop the app, If running in the command windows I have to kill the python app from task manager.
With the following code changes I can exit the app by sending the SIGTERM to proess itself, as both the Flask, and simplehttpserver do not provide an API for exiting the process.

from flask import Flask, request, g, make_response
import queue
import time
import os
from threading import Thread
import signal
import ctypes

from multiprocessing import Process

import sys

OUTPUT_EMPTY_LIMIT = 3 
DEFAULT_PORT = 9090

SHUTDOWN    = False
EXIT_CHARS  = "Qqx11x18"      # 'Q', 'q', Ctrl-Q, ESC


print("Name = {}".format(__name__))

app = Flask(__name__)


def shutdown_app():
    global SHUTDOWN
    SHUTDOWN = True

@app.before_request
def before_request():
    if SHUTDOWN:
        return 'Shutting down...'
    
def run_app(port, host, debug, threaded):
    app.run(port=port, host=host, debug=debug, threaded=threaded)

    
@app.route("/")
def app_help():
    return "Hello, World from help!"

@app.route("/square/<int:number>")
def square(number):
    return str(number**2)

# This doesnt kill the app as well.
@app.route("/stop")
def stop():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the werkzeug Server')
    func()
    return 'Server shutting down...'
    exit(0)

if __name__ == "__main__":
    port = 5000
    host = '0.0.0.0'
    debug = False
    threaded = True   
    process = Process(target=run_app, args=(port, host, debug, threaded))
    process.start()
    
    while True:
        ch = input("Enter 'Q' to stop server and exit: ")
        if (ch == 'Q'):
            break
    
    shutdown_app()
    process.terminate()
    #process.kill()
    #process.join()
    print("Exiting the app")
    # os.kill(os.getpid(), signal.SIGINT)
    os._exit(0)

I am new to Python and have tried both google search and chatGPT to find a way to shutdown Flask App and the web server that is started on a windows operating system.
I have also tried the other answeres on the stack overflow 15562446

I also tried the link Shutdown The Simple Server

Asked By: Amit Bhatia

||

Answers:

I’ve found while testing that werkzeug.server.shutdown does nothing, and it needs to be shutdown using sys.exit(0) on my windows machine.
In your code a value is returned before the exit() is run – therefore it does not shut down. One way to do what you want is using deferred callbacks.

from flask import after_this_request 

@app.get('/stop')
def shutdown():
    @after_this_request
    def response_processor(response):
        @response.call_on_close
        def shutdown():
            import sys
            sys.exit("Stop API Called")
        return response
    return 'Server shutting down...',200
Answered By: arrmansa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.