One of the things that is done a lot in web applications, as far as the server side is concerned, is redirecting content. Let’s see in this article how to perform a Redirect in Flask.
The first thing will be to create a route in which we have content. To do this we rely on the route() annotation.
@app.route('/')
def helloworld():
return 'Hello World!'
In this case we see that the route we are addressing is the root and that the method will be called helloworld(). The name of the method is important since we will not do the redirection to the route but rather to the method.
Now we move on to create a second route, which will have the redirect in Flask.
@app.route('/greeting')
def greeting():
To be able to create the redirect in Flask we are going to rely on the redirect() method, to which we will pass the route to which to redirect. But as we already saw in the article Routes URLs with Flask, we should not use the route (in case we change it) but rather we will have to use the url_for() method to which we will pass the name of the method that has the route to be redirected.
Thus the code with the redirect in Flask we have the following form:
@app.route('/greeting')
def greeting():
return redirect(url_for('helloworld'))
Something very simple, now you just have to access the /greeting route to see what happens and how the redirect works in Flask.
