The only officially documented way of stopping Flask from within the application can only be done with a request context:
from flask import request
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route('/shutdown', methods=['POST'])
def shutdown():
shutdown_server()
return 'Server shutting down...'
This leads to the very ugly and hacky scenario where you pretty much have to script a request from the server to itself if you want it to shut down from another part of the process (ie: not in response to a request and you have no request context). This also exposes the kill endpoint to the whole network (even if it's unimportant / non-prod, still stupid if not necessary).
Is there a clean way of stopping Flask without a request context, ie: the mythological app.stop()
?
For more context, and without diving into the esoteric reasons that have me running Flask in a thread (makes sense for my program, I promise):
class WebServer:
def __init__(self):
self.app = Flask('test')
self.thread = threading.Thread(target=self.app.run)
@self.app.route('/')
def index():
return 'Hello World'
def start(self):
self.thread.start()
def stop(self):
# how can I implement this? just getting Flask to end would end the thread!