Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask abort() inside try block behaviour

Tags:

python

flask

When i want to use the flask abort inside a try block i end up in my exception block

@app.route('/newsletters/<int:newsletter_id>', methods=['GET'])
def route_get_newsletter(newsletter_id):
    if request.method == 'GET':        
        try:
            newsletter = get_newsletter(newsletter_id)                
            if not newsletter:
               abort(404)
        except Exception, ex:
            logging.exception("Something awful happened!")
            abort(500)
        else:            
            return jsonify(newsletter=newsletter)

gives output:

ERROR:root:Something awful happened!
Traceback (most recent call last):
 File "natuurpuntapi.py", line 210, in route_get_newsletter
   abort(404)
 File "/usr/lib/python2.7/dist-packages/werkzeug/exceptions.py", line 525, in __call__
   raise self.mapping[code](*args, **kwargs)
NotFound: 404: Not Found

and werkzeug NotFound is called and i get the 500 response

when i put the abort(404) outside the try: block, it works and i get the 404 response

  • edit

i found that flask abort() uses the werkzeug abort() which is a class called Aborter() when this is called it raises "raise self.mapping[code](*args, **kwargs)"

does this mean i can not call abort inside my own try block because it will raise an exception and ends up in my exception?

like image 473
user1120753 Avatar asked Dec 26 '22 00:12

user1120753


1 Answers

flask.abort(...) raises itself an exception, one of the exceptions described in the docs, all subclasses of werkzeug.exceptions.HTTPException. This is the reason why your code doesn't work.

But here is some other trivia:

  • If your code raises other kinds of exceptions, Flask will automatically return a 500.
  • you can create custom error handlers for HTTP status codes and exceptions: http://flask.pocoo.org/docs/patterns/errorpages/#error-handlers
  • If you have methods=['GET'], you don't need to check for the method inside the view.

Given that knowledge we can rewrite your code like:

@app.route('/newsletters/<int:newsletter_id>', methods=['GET'])
def route_get_newsletter(newsletter_id):
    newsletter = get_newsletter(newsletter_id)
    return jsonify(newsletter=newsletter)

@app.errorhandler(500)
def catch_server_errors(e):
    logging.exception("Something awful happened!")
like image 189
Markus Unterwaditzer Avatar answered Dec 28 '22 12:12

Markus Unterwaditzer