Codementor Events

Custom Error Pages in Flask

Published Aug 11, 2019
Custom Error Pages in Flask

Custom Error Pages for a website shows its creativity and Uniqueness from every other in competitions.

Flask a lightweight WSGI web application framework allows these error page creation in a very simple way.

Suppose we have a simple Hello world application in flask:

from flask import flask, render_template

app = flask(__name__)

@app.route('/')
def index():
  return render_template("hello_world.html")

Error Handlers

An error handler is registered with the errorhandler() decorator and can registered for status codes like 404, 500, 403, 410.

We can use this in simple route:
@app.errorhandler(404)

And now the last part is to create a function passing exception and return a custom error html page, here for 404 error.
@app.errorhandler(404)
def not_found(e):
.....return render_template('custom_page.html'), 404

Here the status code of the response will not be set to the handler’s code. We need to provide the appropriate HTTP status code when returning a response from a handler.

Complete Code:

from flask import flask, render_template

app = flask(__name__)

@app.route('/')
def index():
  return render_template("hello_world.html")
    
@app.errorhandler(404)
def not_found(e):
  return render_template('custom_page.html'), 404
Discover and read more posts from Lakshya Srivastava
get started
post commentsBe the first to share your opinion
Show more replies