Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Flask abort() or returning a status

Tags:

python

flask

What is the difference between abort(400) and returning a response with a 400 status? Is using return bad form for errors?

abort(400, "some error message")
# or
return {'message': "some error message"}, 400
like image 329
Glen Avatar asked Nov 14 '17 14:11

Glen


People also ask

What does abort do in flask?

Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It will also provide a plain black and white error page for you with a basic description, but nothing fancy. Depending on the error code it is less or more likely for the user to actually see such an error.

How do I abort a flask request?

To achieve what you want to do, you have to pass a Response object to the abort method. One of the reasons you'll create a Response object instead of allowing render_template or abort do it for you is when you need to add a custom header to a response or change the default headers that abort adds to the response.

How do I return a flask error?

You could use abort(http_code) to return an appropriate http code to the client or just raise a non-http exception. And use @app. errorhandler() decorator to provide a custom handler for http errors and arbitrary exceptions. You could also use an ordinary try/except block where you are ready to handle an exception.

How do I send my 401 response to a flask?

Create a function whose only argument is the HTTP error status code, make it return a flask. Response instance, and decorate it with @app. errorhandler. You can then use abort(401) to your heart's content.


1 Answers

abort raises an error, which an error handler will convert to a response. return returns a response, error handlers don't trigger. It's up to how you want your application to flow.

like image 149
davidism Avatar answered Oct 04 '22 18:10

davidism