Introduction to Flask redirect
Flask redirect is defined as a function or utility in Flask which allows developers to redirect users to a specified URL and assign a specified status code. When this function is called, a response object is returned, and the redirection happens to the target location with the status code. When a website is visited, server receives a request and after processing responds to the request with a three-digit code known as the HTTP code. In a programming world this status code that is returned as a response is known as Errors. Errors and redirect function goes hand in hand.
Syntax of Flask redirect
In cases of web application interface redirecting is an important step that is required if one needs to route to a designated URL. There are various methodologies in the world of routing about which we will know in greater detail, but in this section we will know about the syntax first.
1. Importing the redirect and abort function.
from flask import redirect, abort
2. Instantiating of Flask redirect.
flask.redirect(<location>,<status-code>, <response> )
- <location>: Denotes the URL location to which the response from the redirect will be routed to.
- <status-code>: Represents the status code which is sent to the header of the browser besides the response from the server.
- <response>: For any future references or requirements of the project, this is the instance that is referred to.
3. Using abort function to exit from the code loop, in conjunction to redirect.
flask.abort( <code> )
Here the code refers to a set of codes that will generate some error, as applicable, and stop any further execution of the application.
How does redirect Function Works in Flask?
Redirect function is one of the big three route resolutions in Flask. We know that any Flask function will have the concept of serving contents through multiple URLs. Routes are the URL where the content is served, and views refers to the content in them. Also, another piece is that the route decorator enables users to list the endpoint along with added functionality of methods that one would expect would happen in the endpoint. Now assume there are multiple users, and we need to create a dynamic URL by their username. For this we can use the concept of dynamic routes. With the dynamic routes and the variable rules, the dynamic URL is created and can be accessed. Now that the route piece is clear, we would need to understand the view responses. The view responses in a Flask application happens in three common ways namely, page template, response and redirecting. We will park the first 2 for some other article, but here we will talk in depth about the redirecting.
In this function we send in a string which corresponds to the path where the user will be redirected to. This string can be either a relative path, an absolute path or even an external URL. The function searches for the corresponding match to the string passed as an argument and correspondingly renders the required template and puts it in front of the user.
Another variation of the redirect function, and the most widely used one, as it is one of the best practices in terms of programming is to route by names rather than by sending in the path of the redirect URL. For this we use a built-in function known as url_for( ) discussed in detail in another article. Onto this we send the name of the view function is passed, the url_for( ) function is responsible for converting the name of the view function to the corresponding URL pattern. One added benefit we would achieve out of this is to prevent any broken links between pages.
Now as a part of redirection, there are status code which can be easily used for communication to the server.
Below is the list of status and what they refer to:
|Status Code||Messaging Significance|
|300||The code refers to the message that indicates requests has more than one response.|
|301||This is to indicate that the resource is moved permanently.|
|302||This the by default message, denoting that the resource is found.|
|303||This is to inform that the response doesn’t redirects to something new, but another page.|
|304||This is o inform that retransmission of the resources is not required.|
|305||This is a depreciated code, typically instructing the server to connect to proxy.|
|306||This code is no longer used now.|
|307||In contrast to the 301, here the resource has been moved temporarily.|
The above codes are used at their convenience to the application that is being built and type of redirect messaging that needs to be done.
Now let us look at one flask application with a redirect capability.
Examples of Flask redirect
Given below are the examples of Flask redirect:
Sample code for redirect functionality.
from flask import Flask, redirect, url_for appFlask = Flask(__name__) @appFlask.route("/home") def home(): return redirect(url_for('LoginPage')) @appFlask.route("/LoginPage") def LoginPage(): return "You are redirected to Login Page" if __name__ == "__main__": appFlask.run(debug=True)
Using abort function to portray unauthorized login.
from flask import Flask, redirect, url_for, abort appFlask = Flask(__name__) @appFlask.route("/home/<user>") def home(user): if user == 'admin': return redirect(url_for('LoginPageAdmin')) else: abort(401) @appFlask.route("/LoginPageAdmin") def LoginPageAdmin(): return "You are redirected to Login Page" if __name__ == "__main__": appFlask.run(debug=True)
For admin login:
For another user login:
Here we see that when the URL has an argument named as admin, we are redirected to the corresponding URL for admin. In case of any other user, we get an unauthorized access pertaining to the fact that the user is unauthorized for redirect.
To conclude, in this article we have looked at the simple way of working for redirect function and also how abort function goes hand in hand with the redirect function. Usage of this functionality is left to readers to try out these concepts in Flask applications. Also, the list of error codes here will come in handy for our readers to use for correct functionality.
This is a guide to Flask redirect. Here we discuss the introduction, how does redirect function works in flask? and examples respectively. You may also have a look at the following articles to learn more –