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.
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.
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.
You can also redirect with a specific HTTP status code. For example, for a permanent redirect (301), you can use:
return redirect('/about', code=301)Errors are bound to happen in any web application. Flask provides a simple way to handle them using error handlers.
You can create custom error pages for different types of errors. Here's how to create a custom error page for a 404 error:
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.
What does the `redirect()` function do in Flask?
How can you redirect with a specific HTTP status code in Flask?