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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from flask import Flask, redirect, url_for, render_template, request
# Initialize the Flask application
app = Flask(__name__)

@app.route('/')
def index():
return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST' and
request.form['username'] == 'admin' :
return redirect(url_for('success'))
return redirect(url_for('index'))

@app.route('/success')
def success():
return 'logged in successfully'

if __name__ == '__main__':
app.run(debug = True)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
if request.form['username'] == 'admin' :
return redirect(url_for('success'))
else:
abort(401)
else:
return redirect(url_for('index'))

@app.route('/success')
def success():
return 'logged in successfully'

if __name__ == '__main__':
app.run(debug = True)

Related course: Python Flask: Create Web Apps with Flask