Change language

Python | 404 Error Handling in Flask

| |

A 404 error is displayed whenever the page is not found. Perhaps the owner changed their URL and forgot to change the link, or perhaps they deleted the page itself. Every site needs a Custom Error page to prevent the user from seeing the Ugly Error page by default.

Python.Engineering also has a custom error page. If we enter a URL like
python.engineering/ajneawnewiaiowjf

Default 404 error

GeeksForGeeks Custom Error Page

It will show a 404 error page as this URL does not exist. But the error page provides a nice layout, helps the user to go back or even take them to the home page after a certain amount of time. This is why Custom Error pages are required for every site.

Flask provides us with a way to handle the error and return to our custom error page.

To do this, we need to download and import the flask. Download the flask with the following commands on the CMD.

 pip install flask 

Using app.py as our Python template management file, 404.html will be the file we will return to in case of 404 error, and header.html will be the file with the title and navigation bar of the website.

app.py
Flask allows us to make a python file to define all routes and functions. In app.py, we defined a route to the main page (& # 39; / & # 39;) and an error handler function, which is a flask function, and we passed the 404 error as a parameter.

from flask import Flask, render_template

 

app = Flask (__ name__)

  
# Application name

@ app . errorhandler ( 404 )

 
# built-in function that takes an error as a parameter

def not_found (e):

 
# defining function

return render_template ( "404.html" )

The above python program returns a 404.html file whenever a user opens a broken link.

404.html
The following code will export the title and navigation bar from header.html.
Both files should be stored in the templates folder according to the flask.

{% extends "header.html"%}
& lt ;! - Exports title and navigation bar from header.html.

or any file you want -"

{% block title%} Page Not Found {% endblock%}
{% block body%}

  

  " h1 " Oops! Looks like the page doesn’t exist anymore "/ h1 "

" a href = "{{url_for (’ index’)}} " " " p " Click Here "/ a " To go to the Home Page "/ p "

 
& lt ;! - {{url_for (& # 39; index & # 39;)}} is a variable that returns the URL index.html -"
{% endblock%}

Auto redirect to home page after 5 seconds

The app.py code for this example remains the same as above.
The following code Displays the Custom 404 error page and starts counting down 5 seconds.
After 5 seconds, it redirects the user back to the home page.
404.html
The following code will export the title and navigation bar from header.html.
Both files should be stored in the templates folder according to the flask.
After 5 seconds, the user will be automatically redirected to the home page.

" html "

" head "

" title " Page Not Found "/ title "

" script language = "JavaScript" type = "text / javascript" "

 
var seconds = 6;
// countdown timer. took 6 because page takes approx 1 sec to load

 
var url = " {{url_for (index)}} ";
// variable for index.html url

 
function redirect () {

if (seconds "= 0) {

 

// redirect to new url after counter down.

window.location = url;

} else {

seconds--;

document.getElementById ("pageInfo"). innerHTML = "Redirecting to Home Page after"

+ seconds + "seconds."

setTimeout ("redirect ()", 1000)

}

}

"/ script "

"/ head "

 
{% extends "header.html"%}
// exporting navbar and header from header.html
{% block body%}

 

" body onload = " redirect () " "

" p id = "pageInfo" " "/ p "

{% endblock%}

 

 

"/ html "

Sample header.html
This is a header.html example that includes a navigation bar as shown in the picture.
It consists of a bootstrap. You can also make your own.
To do this, refer to Bootstrap Documentation .

& lt;! DOCTYPE html"

" html "

" head "

 
& lt ;! - LINKS TO ALL SCRIPTS / CSS REQUIRED FOR NAVBAR -"

 

  " link rel = "stylesheet" href = " https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/

css / bootstrap.min.css "

  integrity = "sha384-Gn5384xqQ1aoWXA + 058RXPxPg6fy4IWvTNh0E26 

3XmFcJlSAwiGgFAW / dAiS6JXm" cross class = "color1"> class = "plain"> = "anonymous" "

 

" title " Flask "/ title "

"/ head "

" body "

" script src = " https://code.jquery.com/jquery-3.2.1.slim.min.js " integrity =

"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr / rE9 / Qpg6aAZGJwFDMVNA / GpGFF93hXpG5KkN"  < code> p>

crossorigin = "anonymous" " "/ script "

 

" script src =" https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd

/ popper.min.js "integrity =" sha384-ApNbgh9B + Y1QKtv3Rn7W3mgPxhU9K

/ ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q class = "color1"> crossorigin = "anonymous" " "/ script "

 

" script src = " https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/ js / bootstrap.min.js "

  integrity = "SHA384-JZR6Spejh4U02d8jOt6vLEHfe / JQGiRRSQQxSfFWpi1MquVdAyjUar5 + 76PVCmYl"

  crossorigin = "anonymous" " "/ script "

 

" header "

& lt ;! - Initial title -"

 

" nav class = "navbar navbar-expand-lg navbar-light bg-light" "

" a class = "navbar-brand" href = " # " " Navbar "/ a "

& lt ;! - bootstrap classes for navbar -"

" button class = "navbar-toggler" type = "button" data-toggle = " collapse " data-target =

"# navbarSupportedContent" aria-controls = "navbarSupportedContent"

  aria-expanded = "false"   aria-label = " Toggle navigation " "

" span class = "navbar-toggler-icon" " "/ span "

"/ button "

 

" div class = "collapse navbar-collapse" id = " navbarSupportedContent " "

" ul class = "navbar-nav mr-auto" "

" li class = "nav-item active" "

" a class = "nav-link" href = " # " " Home " span class = " sr-only " " (current) "/ span & gt ; "/ a "

"/ li "

" li class = "nav-item" "

" a class = "nav-link" href = " # " " Link "/ a "

"/ li "

" li class = "nav-item dropdown" "

  " a class = "nav-link dropdown-toggle" href = "#" id = "navbarDropdown"

role = "button data-toggle =" dropdown " aria-haspopup = " true " aria-expanded = " false " "

Dropdown

"/ a "

" div class = "dropdown-menu" aria-labelledby = " navbarDropdown " "

" a class = "dropdown-item" href = " # " " Action "/ a "

" a class = "dropdown-item" href = " # " " Another action "/ a "

" div class = "dropdown-divider" " "/ div "

" a class = "dropdown-item" href = " # " " Something else here "/ a "

"/ div "

"/ li "

" li class = "nav-item" "

" a class = "nav-link disabled" href = " # " " Disabled "/ a "

"/ li "

"/ ul "

" form class = "form-inline my-2 my-lg-0" "

" input class = "form-control mr-sm-2" type = "search"

placeholder = "Search" aria-label = "Search" "

" button class = "btn btn-outline-success my-2 my-sm-0 " 

  type = "submit" " Search "/ button "

"/ form "

"/ div "

"/ nav "

"/ head "

 

" body "

 

{% block body%}

  

  {% endblock%}

 

"/ body "

"/ html "

Output:
The output will be a custom error page with header.html that the user exported.
Below is a sample output with my custom header, footer and 404.html file.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically