The Flask class has a redirect()
function. When invoked, it returns a response object and redirects the user to another target location with the specified status code.
Sometimes you need to redirect an URL, like when the url is no longer available or the user is not logged in. The redirect
function lets you do that in Flask.
Related course: Python Flask: Create Web Apps with Flask
Flask redirect
Redirect function
The syntax of the redirect()
function is as follows:
1 | Flask.redirect(location, statuscode, response) |
In the above functions:
- The location parameter is the URL where the response should be redirected.
- statuscode is sent to the browser header by default 302.
- The response parameter is used to instantiate the response.
Status codes
The following status codes are standardized:
- HTTP 300: MULTIPLE_CHOICES
- HTTP 301: MOVED_PERMANENTLY
- HTTP 302: FOUND
- HTTP 303: SEE_OTHER
- HTTP 304: NOT_MODIFIED
- HTTP 305: USE_PROXY
- HTTP 306: RESERVED
- HTTP 307: TEMPORARY_REDIRECT
- HTTP 302: NOT FOUND
1 | from flask import Flask, redirect, url_for, render_template, request |
Errors
Error codes
The Flask class has an abort()
function with error codes.
1 | Flask.abort(code) |
The Code parameter takes one of the following values:
- 400 - for error requests
- 401 - Used for unauthenticated
- 403 - Forbidden
- 404 - Not
- 406 - Not accepted
- 415 - for unsupported media types
- 429 - Too many requests
Redirect example
Example
Let us make a slight change to the login()
function in the above code.If you want to display the ‘Unauthorized’ page, replace it with call abort(401)
instead of redisplaying the login page.
1 | from flask import Flask, redirect, url_for, render_template, request, abort |
Related course: Python Flask: Create Web Apps with Flask