how to close a flask web server with python

from flask import Flask

app = Flask(__name__)

def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':

# 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:

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

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

    # 5. To close the server, send a POST request to the /shutdown route
    shutdown_url = ''

    # 6. Wait for the server thread to finish

Make sure to replace '' with the appropriate URL if your Flask server is running on a different host or port.