Flask Redirect


Set up URL Redirects with Python Flask. This article will address how to use flask redirect in our application.

Why are redirects necessary?

The redirect function majorly alters the URL of a page changing it to another one. All web applications need redirect functions to work more effectively. For instance when you enter the URL of a website and it redirects you to a different page on the web page.

Another instance is when you make payments on an online payment website, it redirects you to the payment confirmation page. It also helps to make URLs shorter. If you click on a short URL, say, https://bit.ly, then it redirects you to a page with a longer one.

Related course: Create Web Apps with Python Flask

Btw, you can easily Deploy your Flask app online

Flask redirect

Before we proceed to create an application with the redirect function, let us look at the redirect syntax.

Syntax of Flask redirect attribute

redirect(location, code, response = None)

where:

  • Location refers to the eventual location to be redirected to.
  • Status Code: This shows the output of the redirect function. It defaults to 302
  • Response: This is applicable when initiating the response.

Let us focus on status codes for now. Some of them are:

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

The redirect function must be added before adding the status code.

from flask import redirect

How to deal with errors in redirect

There is an abort() function commonly used for failures that arise from special redirect failure cases. The syntax for abort() function: abort(<error_code>) The common Error Codes are as follows:

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

Error Codes The abort () has to be imported as well.

from flask import abort

Coding the application The code is as follows:

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.

After submitting the form, the data is sent with the request, to the Verify View. (check the form.html – action attribute)

The Verify View extracts the name data file from the form and the user is redirected to the User View (along with the name data).

Read our article on Flask syntax to gain a better understanding of the codes. 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>

The flask form gathers user data and redirects it to a page showing the name entered on the web page. The sequence is as explained below:

The form function shows the Form. The name is extracted from the form using the verify function and is redirected to the user function and the name is taken as an argument and then displayed on the web page.

Conclusion

We've come to the end of the article. You can experiment with the abort() function so you can get a good handle on code.

Related course: Create Web Apps with Python Flask