how to close a flask web server with python

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()

# To close the Flask web server programmatically, you can use the following approach:

# 1. Import the necessary modules
import requests
import threading

# 2. Define a function to send a request to the Flask server to shut down
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is not None:
        func()

# 3. Create a route to trigger the shutdown function
@app.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

# 4. Run the Flask app in a separate thread
if __name__ == '__main__':
    server_thread = threading.Thread(target=app.run)
    server_thread.start()

    # 5. To close the server, send a POST request to the /shutdown route
    shutdown_url = 'http://127.0.0.1:5000/shutdown'
    requests.post(shutdown_url)

    # 6. Wait for the server thread to finish
    server_thread.join()

Make sure to replace 'http://127.0.0.1:5000/shutdown' with the appropriate URL if your Flask server is running on a different host or port.