url_for() Function in Flask

Another method you can use when performing redirects in Flask is the url_for() function URL building. This function accepts the name of the function as the first argument, and the function named user(name) accepts the value through the input URL. It checks whether the received argument matches the ‘admin’ argument or not. If it matches, then the function hello_admin() is called else the hello_guest() is called.

Python3




from flask import Flask, redirect, url_for
 
app = Flask(__name__)
 
# decorator for route(argument) function
@app.route('/admin')
# binding to hello_admin call
def hello_admin():
    return 'Hello Admin'
 
@app.route('/guest/<guest>')
# binding to hello_guest call
def hello_guest(guest):
    return 'Hello %s as Guest' % guest
 
@app.route('/user/<name>')
def hello_user(name):
 
    # dynamic binding of URL to function
    if name == 'admin':
        return redirect(url_for('hello_admin'))
    else:
        return redirect(url_for('hello_guest'
                                , guest=name))
 
if __name__ == '__main__':
    app.run(debug=True)


Output:

hello_guest function

hello_user function



Redirecting to URL in Flask

Flask is a backend server that is built entirely using Python. It is a  framework that consists of Python packages and modules. It is lightweight which makes developing backend applications quicker with its features. In this article, we will learn to redirect a URL in the Flask web application.

Similar Reads

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....

url_for() Function in Flask

...

Contact Us