Redirection in Flask

Redirections are widely used within Flask applications for managing user authentication, form submissions, and sending users to different pages. Flask’s redirect function allows developers to send users to specific routes. In this tutorial, we will look at how to perform redirection in Flask.

Redirection in Flask is a process where the server instructs the client’s browser to navigate to a different URL.

How to perform redirection in Flask

This is achieved using Flask’s redirect function.

In Flask, the redirect function directs the user to a different endpoint.

Syntax:

flask.redirect(location,code=302)

Parameters:

  • location (str) – The URL to redirect to.
  • code (int) – The status code for the redirect.

Let’s understand this with an example:

from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def home():
    return redirect('https://www.google.com') #default code is 302
if __name__ == '__main__':
    app.run(debug=True,port=9000)

Now, on typing the IP address of the webpage (here it is localhost), it automatically redirects to ‘google.com’.

flask redirection

Add parameter to routing function in Flask

Let’s look at another example

from flask import Flask, render_template,redirect, url_for,request

app = Flask(__name__)

@app.route('/<name>')
def home(name):
    if name=='Red':
        return redirect('https://www.google.com')
    else:
        return 'Inappropriate Name'

In this instance, we provide a parameter to the routing function so that it will redirect to “google.com” if the parameter is “Red,” otherwise it will display a related message.

parameter in flask routing function

Redirection in Flask

Additionally, we also use url_for() function that generates a URL for an end-point, the URL rule name in app.route().

Let’s understand with a small example

from flask import Flask,redirect, url_for
app = Flask(__name__)

@app.route('/')
def index(): 
    return 'Welcome to home page!'

@app.route('/new')
def new(): 
    return 'Welcome to new page!'

@app.route('/rednew')
def abc():
    return redirect(url_for('new'))   

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

url_for() in flask

 

routing in flask

Initially, we are at the home page. Next, as we route to ‘/new’ we move to the new page. On routing to ‘/rednew’ , the view redirects back to ‘/new’.

Practical Applications

  • Post-Submission Handling: Avoiding duplicate form submissions, reroute to a thank-you page following the processing of a form submission.
  • Authentication Management: If a user tries to access a restricted area without the required authentication, send them to a login page.
  • URL Restructuring: To maintain SEO benefits when URLs change, we use redirection, therefore, redirecting users and search engines to the new URLs.

Also read: Flask-Cookies explained and how to use them?

Leave a Reply

Your email address will not be published. Required fields are marked *