How to Stop Flask Application Without Using Ctrl-C

How to stop flask application without using ctrl-c

If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at Shutdown The Simple Server):

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.get('/shutdown')
def shutdown():
shutdown_server()
return 'Server shutting down...'

Here is another approach that is more contained:

from multiprocessing import Process

server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()

Let me know if this helps.

How do I terminate a flask app that's running as a service?

I recommend you use http://supervisord.org/. Actually not work in Windows, but with Cygwin you can run supervisor as in Linux, including run as service.

For install Supervisord: https://stackoverflow.com/a/18032347/3380763

After install you must configure the app, here an example: http://flaviusim.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/ (Is not necessary that you use Nginx with the Supervisor's configuration is enough)

How to stop flask application without using ctrl-c

If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at Shutdown The Simple Server):

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.get('/shutdown')
def shutdown():
shutdown_server()
return 'Server shutting down...'

Here is another approach that is more contained:

from multiprocessing import Process

server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()

Let me know if this helps.

Python Flask app not exiting with sys exit

I think there's no bug.

As flask is probably catching all exceptions in order to do not stop the main process from serving the application.

As you mention, using os._exit(0) does the work.

As far as I've seen, it's catched by python2.7/SocketServer.py:

598         try:
599 self.finish_request(request, client_address)
600 self.shutdown_request(request)
601 except:
602 self.handle_error(request, client_address)
603 self.shutdown_request(request)

Which basically catches everything but handles an error.

BTW: Am I the only one who thinks that this could be refactored with a try/except/finally?



Related Topics



Leave a reply



Submit