Redirect to a URL in Flask
A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server, and the server replies with what is known as the HTTP status code, which is a three-digit number.
Syntax of Redirect in Flask
Syntax: flask.redirect(location,code=302)
Parameters:
- location(str): the location which URL directs to.
- code(int): The status code for Redirect.
- Code: The default code is 302 which means that the move is only temporary.
Return: The response object and redirects the user to another target location with the specified code.
The different types of HTTP codes are:
Code |
Status |
---|---|
300 | Multiple_choices |
301 | Moved_permanently |
302 | Found |
303 | See_other |
304 | Not_modified |
305 | Use_proxy |
306 | Reserved |
307 | Temporary_redirect |
How To Redirect To Url in Flask
In this example, we have created a sample flask application app.py. It has two routes, One is the base route \ and another is \helloworld route. Here when a user hits the base URL \ (root) it will redirect to \helloworld.
app.py
Python3
# import flast module from flask import Flask, redirect # instance of flask application app = Flask(__name__) # home route that redirects to # helloworld page @app .route( "/" ) def home(): return redirect( "/helloworld" ) # route that returns hello world text @app .route( "/helloworld" ) def hello_world(): return "<p>Hello, World from \ redirected page.!< / p>" if __name__ = = '__main__' : app.run(debug = True ) |
Output:
We hit the base URL in the browser as shown below. As soon we hit the URL flask application returns the redirect function and redirects to the given URL.
Contact Us