Build Your Own 404 Error Page Using Flask and Python

Posted by

Create your own 404 page in Flask | Python

Create your own 404 page in Flask | Python

Flask is a micro-web framework for Python that allows you to quickly build web applications. One common task when building a web application is creating a custom 404 page for when a user tries to access a page that doesn’t exist. In this article, we’ll walk through how to create your own custom 404 page in Flask using Python.

Step 1: Set up your Flask app

First, we need to set up a basic Flask app. Create a new file called app.py and add the following code:


  from flask import Flask
  app = Flask(__name__)

  @app.route('/')
  def index():
      return 'Hello, World!'

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

Step 2: Create the custom 404 page

Next, we need to create a custom 404 page. Add the following code to the app.py file:


  @app.errorhandler(404)
  def not_found_error(error):
      return 'Custom 404 page', 404
  

Now, if a user tries to access a page that doesn’t exist, they will see the message “Custom 404 page” instead of the default Flask 404 page.

Step 3: Add some style to your custom 404 page

To make your custom 404 page look better, you can add some simple styling using CSS. Add the following code to a new file called style.css:


  body {
      font-family: Arial, sans-serif;
      text-align: center;
      padding: 50px;
  }

  h1 {
      color: #ff0000;
  }
  

Then link the CSS file to your app.py file:


  <link rel="stylesheet" type="text/css" href="style.css">
  

Conclusion

Creating your own custom 404 page in Flask is a simple way to improve the user experience of your web application. By following the steps outlined in this article, you can easily create a custom 404 page that matches the look and feel of the rest of your app.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@canaldeciruelos2563
10 months ago

great dude thanks

@zetbit
10 months ago

Support by hitting 2 buttons! Like and Subscribe 👏