Book Image

Flask Framework Cookbook

By : Shalabh Aggarwal
Book Image

Flask Framework Cookbook

By: Shalabh Aggarwal

Overview of this book

Table of Contents (19 chapters)
Flask Framework Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating custom 404 and 500 handlers


Every application throws errors to users at some point of time. These errors can be due to the user typing a wrong URL (404), application overload (500), or something forbidden for a certain user to access (403). A good application handles these errors in an interactive way instead of showing an ugly white page, which makes no sense to most users. Flask provides an easy-to-use decorator to handle these errors.

Getting ready

The Flask app object has a method called errorhandler(), which enables us to handle our application's errors in a much more beautiful and efficient manner.

How to do it…

Consider the following code snippet:

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

Here, we have created a method that is decorated with errorhandler() and renders the 404.html template whenever the 404 Not Found error occurs.

The following lines of code represent the flask_catalog_template/my_app/templates/404.html template, which...