Flask Tutorials: Redirects and Errors

beginner
17 min

Flask Tutorials: Redirects and Errors

Welcome to the Flask tutorial on Redirects and Errors! In this lesson, we'll explore how to handle redirects and errors in Flask web applications.

Redirects 🎯

A redirect is a response sent from a web server to a client (typically a web browser) to instruct it to move to a different web page or URL. In Flask, we can use the redirect() function to create redirects.

Redirecting to a new URL 💡

python
from flask import Flask, redirect app = Flask(__name__) @app.route('/') def home(): return redirect('/about') @app.route('/about') def about(): return 'About page' if __name__ == '__main__': app.run()

In the above example, when we access the root URL ('/'), the home() function returns a redirect to the /about URL.

Redirecting with a status code 📝

You can also redirect with a specific HTTP status code. For example, for a permanent redirect (301), you can use:

python
return redirect('/about', code=301)

Errors 📝

Errors are bound to happen in any web application. Flask provides a simple way to handle them using error handlers.

Custom Error Pages 🎯

You can create custom error pages for different types of errors. Here's how to create a custom error page for a 404 error:

python
from flask import Flask, abort, render_template app = Flask(__name__) @app.route('/<path:path>') def catch_all(path): return f'Page not found: {path}' @app.errorhandler(404) def not_found_error(error): return render_template('404.html'), 404 if __name__ == '__main__': app.run()

In the above example, we catch all requests and return a custom message for any path that doesn't exist. Additionally, we create an error handler for the 404 error, which renders a template called 404.html with a status code of 404.

Quiz

Quick Quiz
Question 1 of 1

What does the `redirect()` function do in Flask?

Quick Quiz
Question 1 of 1

How can you redirect with a specific HTTP status code in Flask?