shutdown flask server with request
from flask import Flask, request
app = Flask(__name__)
@app.route('/shutdown', methods=['POST'])
def shutdown():
shutdown_func = request.environ.get('werkzeug.server.shutdown')
if shutdown_func is None:
raise RuntimeError('Not running with the Werkzeug Server')
shutdown_func()
return 'Server shutting down...'
if __name__ == '__main__':
app.run()
Explanation:
Import Flask and Request: The code imports necessary modules from Flask, which is a web development framework for Python. The
Flask
module is for creating the web application, andrequest
is for handling incoming requests.Create an instance of Flask:
app = Flask(__name__)
creates an instance of the Flask class, representing the web application.Define a route for shutdown:
@app.route('/shutdown', methods=['POST'])
decorator is used to create a route/shutdown
that accepts only POST requests.Shutdown Function: The
shutdown()
function is defined to handle the POST request to the/shutdown
endpoint.Retrieve Shutdown Function:
shutdown_func = request.environ.get('werkzeug.server.shutdown')
tries to retrieve the shutdown function from the request's environment.Check Shutdown Function Existence: The code checks if the shutdown function is available. If it doesn't exist, it raises a
RuntimeError
.Execute Shutdown Function:
shutdown_func()
is called to shut down the Flask server.Return Response: After shutting down the server, the function returns a message indicating the server is shutting down.
Run the Flask App:
app.run()
starts the Flask development server if the script is executed directly, allowing the application to handle incoming requests.