Fix Python – How to stop flask application without using ctrl-c

Question

Asked By – vic

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.

Now we will see solution for issue: How to stop flask application without using ctrl-c


Answer

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.

This question is answered By – Zorayr

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0