Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - How to create custom abort() code?

Flask has a good error handler by using abort() or when the error truly occurred.

From Flask documentation there is an example for error 404 handler:

@app.errorhandler(404) def not_found(error):     return render_template('404.html'), 404 

So, I tried to create custom error code like

if False:     abort(777)  @app.errorhandler(777) def something_is_wrong(error):     return render_template('777.html'), 777 

But it does not work and the Werkzeug debugger says: LookupError: no exception for 777

I found this question which says I should do it like this:

if False:     return '777 error', 777 

Unfortunately, the code above produce white-screen, even the Werkzeug debugger does not come out

I know I can simply do:

if False:     return render_template('777.html') 

But it will make the code cleaner if I use the abort(). Is there any way to create custom error code?

like image 202
hrsetyono Avatar asked Sep 05 '12 16:09

hrsetyono


People also ask

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.

What is abort 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 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

The list of possible HTTP status codes is fixed by the Internet Assigned Numbers Authority, so you cannot add a custom one. Werkzeug recognizes this and tries to stop you sending a meaningless code to the browser. Look through the list of status codes to find one that matches your error and use that one.

Edit: Adding status codes to Werkzeug/Flask

import werkzeug.exceptions as ex from flask import Flask, abort  class PaymentRequired(ex.HTTPException):     code = 402     description = '<p>You will pay for this!</p>'  abort.mappings[402] = PaymentRequired  app = Flask(__name__)  @app.route('/') def mainpage():     abort(402)  @app.errorhandler(402) def payme(e):     return 'Pay me!'  app.run() 
like image 84
Abe Karplus Avatar answered Sep 21 '22 02:09

Abe Karplus