How to stop flask application without using ctrl-c

vic picture vic · Mar 22, 2013 · Viewed 133.9k times · Source

I want to implement a command which can stop flask application by using flask-script. I have searched the solution for a while. Because the framework doesn't provide "app.stop()" API, I am curious about how to code this. I am working on Ubuntu 12.10 and Python 2.7.3.

Answer

Zorayr picture Zorayr · Jun 11, 2013

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.route('/shutdown', methods=['POST'])
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.