Flask – Binding URL

First thing that comes to mind when we hear binding is – I guess – BOOKBINDING / PAPER BINDING. Well, this is something similar to that but not exactly. Here, in Flask, binding URL means adding functionalities to some URL.
url_for() is a very useful function used to dynamically build URLs for a specific function. It accepts the first parameter to be the function that needs to be bind, followed by one or more keyword arguments, each corresponding to the variable part of the URL.

Python Code

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<name>')
def hello_user(name):
   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)

In the above example see that the redirect() function is being used to navigate the page to url_for() function page. 
The above script shows a function user(name) that accepts data from a variable to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is moved to the hello_admin() function using url_for(), otherwise, it is moved to the hello_guest() function passing the received argument as a guest parameter to it.

When you run the code, launch browser, and open URL − http://localhost:5000/user/admin you will get an output –

Hello Admin

Now use this URL to see the change – http://localhost:5000/user/Vikash you will get output as – 

Hello Vikash as Guest 
So now, when we know the few basic things of Flask, it'll become even easy and better to move forward..