Issue
I would like to stop my flask server as soon as an unhandled exception occurs. Here is an example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
1/0 # argh, exception
return 'Hello World!'
if __name__ == '__main__':
app.run(port=12345)
If you run this and go to localhost:12345, your browser tells you "internal server error" and the python console logs a DivisionByZero
exception.
But the server app doesn't crash. Flask wraps your routes into its own error handling and it only prints the exception.
I would like to make the server stop as soon as a route produces an exception. But I didn't find this behaviour in the API. You can specify an errorhandler but that is only to give custom error messages to the client after your route failed.
Solution
Stopping Flask requires getting into Werkzeug internals. See http://flask.pocoo.org/snippets/67/
Extracted from a single-user app:
from flask import request
@app.route('/quit')
def shutdown():
...
shutdown_hook = request.environ.get('werkzeug.server.shutdown')
if shutdown_hook is not None:
shutdown_hook()
return Response("Bye", mimetype='text/plain')
The shutdown_hook
bit is what you'd need in an exception handler.
Answered By - Dave W. Smith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.