Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Flask Redirect – Set up URL Redirects with Python Flask

Flask Redirect

In this tutorial, we will learn about flask redirect and how to use it in our application.

Why do we need to set up redirects?

Before going to the implementation, let us first know what redirecting actually is!

So as the name suggests, the redirect function, when called, basically redirects the Webpage to another URL.

It is an essential part of web applications and also increases the efficiency of the application.

  • Take an example of Twitter; if you are not already logged in, then when you hit the Twitter URL (www.twitter.com), you are redirected to the log-in page first. Here the redirect function plays its role.
  • Similarly, during an online transaction, once the payment is made, you are redirected to the confirmation page.
  • Another benefit of redirecting is that it helps in URL shortening—for example, https://bit.ly. Here you type a short URL and are then redirected to the original long one. 

Now that we know why it is used let’s move onto the Hands-on section.

Implementing a Flask Redirect

Now we will code a little application using the Flask redirect function. But first, we will see the redirect function syntax.

1. Syntax of Flask redirect attribute

The syntax for redirect:

redirect(location, code, response = None)

where:

  • location: Target location of the final webpage
  • Status Code: These are the HTTP redirect status code, to indicate the output of the action. Defaults to 302
  • Response: Response calss to use when initiating the response.

We dont need to care much about the last one right now. Some of the other status codes are:

Status CodeHTTP meaning
300Multiple Choices
301Moved Permanently
302Found
303See Other
304Not Modified
305Use Proxy
306Reserved
307Temporary Redirect

Note: We first need to import the redirect attribute before using it.

from flask import redirect

2. Error Handling for Redirect

Flask also has a abort() function for the special redirect failure cases.

The syntax for abort() function:

abort(<error_code>)

The various Error Codes are as follows:

Error CodeMeaning
400 Bad Request
401Unauthenticated
403Forbidden
404Not Found
406Not Acceptable
415Unsupported Media Type
429Too Many Requests
Error Codes

Note: We need to import this attribute first as well.

from flask import abort

3. Code for our application

Now consider the following example code:

from flask import Flask,render_template,request,redirect

app = Flask(__name__)

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

@app.route('/verify', methods = ['POST', 'GET'])
def verify():
    if request.method == 'POST':
        name = request.form['name']
        return redirect(f"/user/{name}")

@app.route('/user/<name>')
def user(name):
    return f"Your name is {name}"


app.run(host='localhost', port=5000)

Here:

  • The Form View simply displays the Form Template to the user.
  • When the user submits the Form, the form data is sent, along with request, to the Verify View. (Look at form.html – action attribute)
  • The Verify View, pulls out the name data from the form and then redirects the user to the User View (along with the name data).

Do check out our Introduction to Flask article if you have any trouble understanding the syntax.

The form.html is:

<form action="/verify" method = "POST">
    <p>name <input type = "text" name = "name" /></p>
    <p><input type = "submit" value = "Submit" /></p>
</form>

We are using a Flask form to take input from the user and then redirect it to a webpage showing the name back.

Here, the sequence is:

  • The form function shows the Form.
  • Once the user submits his name, the verify function pulls out the name from the Form and redirects him to the User function.
  • The User function takes in the name as an argument and shows it on the webpage.

4. Implementation of the Code

Now run the server and check it out

Form
Form

Hit submit

Redirect
Redirect

That’s it guys !! The name is appearing up there.

Conclusion

That’s it guys for this tutorial !! Try to figure out how to include the abort function in your code as a practise.

We will see you guys in the next article !! Till then, Happy coding 🙂