2

I'd like to be able to terminate my flask app remotely with an http request like this:

import flask
import sys

master = flask.Flask(__name__)

@master.route('/shutdown')
def shutdown():
    #do things
    sys.exit()

if __name__ == '__main__':
    master.run()

Thing is it just doesn't work. From the terminal I get nothing, as if it's not even processing the request. I know that sys.exit() just raises a SystemExit, so I think it may be that it gets caught somewhere. The fact that os._exit(0) does work also leads me to think so.

Am I tripping on something stupid? Is it actually a bug and there is a workaround? I'd prefer not to use os._exit(0) if possible. Thanks!

Edit: I wouldn't say this question is a duplicate since the accepted answers differ and the other one is from '13 (Flask's gone a long way in the meantime)

marvin
  • 33
  • 3
  • 6

1 Answers1

2

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?

David Garaña
  • 915
  • 6
  • 8