Search code examples
pythonhttpflaskerror-handlinghttp-error

Flask - make `abort` use plain text


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?


Solution

  • 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)