In this tutorial we're going to cover the basics of handling redirects and creating custom error pages in Flask. This is an important aspect of web development as it provides a better user experience, guiding users through our site and presenting them with helpful information when something goes wrong.
What We'll Learn:
- How to handle redirects in Flask.
- How to create custom error pages in Flask.
Prerequisites:
- Basic knowledge of Python.
- Familiarity with Flask. If you're new to Flask, you can check out the official Flask tutorial.
Handling Redirects in Flask:
In Flask, we handle redirects using redirect() function. It generates a response with a location header and a 302 status code.
Creating Custom Error Pages in Flask:
We can create custom error pages in Flask using the errorhandler() decorator. It allows us to specify a function to handle specific HTTP error codes.
In the next section, we'll walk through some examples of these concepts.
Example 1: Basic Redirect
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def home():
    return redirect(url_for('hello_world'))
@app.route('/hello')
def hello_world():
    return 'Hello, World!'
In this example, when users access the '/' route, they are redirected to the '/hello' route.
Example 2: Custom Error Page
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404
In this example, when users access a page that doesn't exist (i.e., they receive a 404 error), they are directed to a custom '404.html' page.
In this tutorial, we learned how to handle redirects in Flask using redirect() and url_for(), and how to create custom error pages using errorhandler(). These are essential tools for improving user experience on your website.
For further learning, you can explore other HTTP status codes and how to handle them in Flask.
Exercise 1: Create a Flask app that redirects users from '/old' route to '/new' route.
Solution:
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/old')
def old():
    return redirect(url_for('new'))
@app.route('/new')
def new():
    return 'Welcome to the new page!'
Exercise 2: Create a Flask app with a custom error page for 500 (Internal Server Error).
Solution:
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(500)
def internal_error(error):
    return render_template('500.html'), 500
Remember, it's always a good practice to have custom error pages for common HTTP status codes. This will make your website more user-friendly.