Home > other >  Flask - make `abort` use plain text
Flask - make `abort` use plain text

Time:11-04

I am using Flask's abort function in my API methods to prematurely stop execution and return an error:

abort(404, errMsg)

This returns errMsg inside a preformatted HTML template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>(errMsg)</p>

However, since I am building an API, not a webpage, I want the error to be returned as plain text instead. I have seen the docs page on custom error pages, but I'd rather redefine abort once for every error, rather than having to define it for each error code. Is there a way to do this?

CodePudding user response:

You can change the werkzeug.exceptions.HTTPException.get_body (the method used to get that formatted HTML) to your own get_body function and return the plain text.
And it is still easy to change the error message for users.

from flask import Flask, abort
import werkzeug.exceptions


def get_body(self, environ=None, scope=None):
    return f'{self.code}, {self.name}, {self.description or ""}'


werkzeug.exceptions.HTTPException.get_body = get_body

app = Flask(__name__)


@app.route('/')
def home():
    abort(404)


@app.route('/nothome')
def not_home():
    abort(500, 'some server error happened')


if __name__ == '__main__':
    app.run(debug=True)

CodePudding user response:

Instead of redefining internal werkzeug classes, you can instead provide a Response object to abort:

from flask import abort as fabort

def abort(status_code, message):
    response = make_response(f'{status_code}\n{message}')
    response.status_code = status_code
    fabort(response)
  • Related