r/flask 10d ago

Ask r/Flask Displaying HTTP response code in Jinja

I want to display the response code sent from my Flask backend (e.g. 400 200 201 etc.) in Jinja - how can I access this?

1 Upvotes

1 comment sorted by

1

u/1NqL6HWVUjA 10d ago

Assuming you're dealing with an instance of a Werkzeug HTTPException — which you are if you're doing something like abort(404) — then the code attribute contains the HTTP status code.

Here's a relatively minimal working example of custom error handlers that render a template:

from flask import current_app, Flask, render_template_string
from werkzeug.exceptions import HTTPException

# In practice, this would be an HTML file with more styling and content. 
# It's a string here so the example is self-contained. 
ERROR_TEMPLATE = r"""<!DOCTYPE html>
<html>
    <head>
        <title>Oopsie</title>
    </head>
    <body>
        <h1>{{status_code}} Error</h1>
        <p>{{description}}</p>
    </body>
</html>"""

def handle_http_exception(exc:HTTPException):
    """Use the code and description from an HTTPException to inform the user of an error"""
    return render_template_string(ERROR_TEMPLATE, status_code=exc.code, description=exc.description)

def handle_uncaught_exception(exc:Exception):
    """Log the exception, then return a generic server error page."""
    current_app.log_exception(exc)
    return render_template_string(ERROR_TEMPLATE, status_code=500, description='Internal server error')

def raise_example_exception():
    """Used to test uncaught exception error handler."""
    raise ValueError('Example exception')

def create_app():
    app = Flask(__name__)
    # This handler is run when an HTTPException, or any of its subclasses, is raised
    app.register_error_handler(HTTPException, handle_http_exception)
    # This handler is run for all other uncaught exceptions
    app.register_error_handler(Exception, handle_uncaught_exception)
    # Register a generic landing route to verify the app is running
    app.add_url_rule('/', 'landing', lambda: 'Landing page')
    # Register a route that results in an exception, to test error handler
    app.add_url_rule('/example-error', 'example_error', raise_example_exception)
    return app

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