In this section, we will learn how to create custom error pages in Flask. Custom error pages enhance the user experience by providing friendly and informative messages when something goes wrong. We will cover the following topics:
- Understanding Error Handlers
- Creating Custom Error Templates
- Implementing Custom Error Handlers
- Practical Example
- Exercises
- Understanding Error Handlers
Flask allows you to define custom error handlers for different HTTP status codes. Common status codes include:
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: An unexpected server error occurred.
Error handlers are functions that Flask calls when an error occurs. You can use these handlers to render custom templates or perform other actions.
- Creating Custom Error Templates
First, let's create custom templates for our error pages. These templates will be stored in the templates
directory.
Example: 404 Error Template
Create a file named 404.html
in the templates
directory with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page Not Found</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 50px; } h1 { font-size: 50px; } p { font-size: 20px; } </style> </head> <body> <h1>404</h1> <p>Oops! The page you are looking for does not exist.</p> <a href="/">Go to Home</a> </body> </html>
Example: 500 Error Template
Create a file named 500.html
in the templates
directory with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Server Error</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 50px; } h1 { font-size: 50px; } p { font-size: 20px; } </style> </head> <body> <h1>500</h1> <p>Sorry! Something went wrong on our end.</p> <a href="/">Go to Home</a> </body> </html>
- Implementing Custom Error Handlers
Now, let's implement the custom error handlers in our Flask application. We will use the @app.errorhandler
decorator to define these handlers.
Example: Custom Error Handlers
Add the following code to your Flask application:
from flask import Flask, render_template app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 if __name__ == '__main__': app.run(debug=True)
In this example:
- The
page_not_found
function handles 404 errors and renders the404.html
template. - The
internal_server_error
function handles 500 errors and renders the500.html
template.
- Practical Example
Let's create a simple Flask application that includes custom error pages.
Step-by-Step Example
- Create the Flask Application
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the Home Page!' @app.route('/cause-500') def cause_500(): # This route will intentionally cause a 500 error raise Exception("Intentional Exception") @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 if __name__ == '__main__': app.run(debug=True)
- Create the Error Templates
Ensure you have the 404.html
and 500.html
templates in the templates
directory as described earlier.
- Run the Application
Run the Flask application and test the custom error pages by navigating to non-existent routes and the /cause-500
route.
- Exercises
Exercise 1: Custom 403 Error Page
- Create a custom template for a 403 Forbidden error.
- Implement an error handler for the 403 error in your Flask application.
- Test the custom 403 error page by creating a route that triggers a 403 error.
Solution
- Create the 403 Template
<!-- templates/403.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Forbidden</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 50px; } h1 { font-size: 50px; } p { font-size: 20px; } </style> </head> <body> <h1>403</h1> <p>You do not have permission to access this page.</p> <a href="/">Go to Home</a> </body> </html>
- Implement the Error Handler
- Test the Custom 403 Error Page
Add a route that triggers a 403 error:
Navigate to /cause-403
to see the custom 403 error page.
Conclusion
In this section, we learned how to create custom error pages in Flask. We covered:
- Understanding error handlers
- Creating custom error templates
- Implementing custom error handlers
- A practical example
- Exercises to reinforce the concepts
Custom error pages improve the user experience by providing informative and user-friendly messages when errors occur. In the next section, we will explore logging and debugging in Flask to help you troubleshoot and resolve issues in your applications.
Flask Web Development Course
Module 1: Introduction to Flask
- What is Flask?
- Setting Up Your Development Environment
- Creating Your First Flask Application
- Understanding Flask Application Structure
Module 2: Basic Flask Concepts
- Routing and URL Mapping
- Handling HTTP Methods
- Rendering Templates with Jinja2
- Working with Static Files
Module 3: Forms and User Input
Module 4: Database Integration
- Introduction to Flask-SQLAlchemy
- Defining Models
- Performing CRUD Operations
- Database Migrations with Flask-Migrate
Module 5: User Authentication
Module 6: Advanced Flask Concepts
Module 7: RESTful APIs with Flask
Module 8: Deployment and Production
- Configuring Flask for Production
- Deploying to Heroku
- Deploying to AWS
- Monitoring and Performance Tuning