Flask URL Building

In the URL building, we use the  url_for() function to create a URL for a specific function dynamically. As its first argument, it accepts the name of the function and any number of keyword arguments, every corresponding to a variable part of the URL rule. All Unknown parts of the variable are attached as query parameters to the URL.

Flask makes it easy for the user to add the variable part to the URL via the section. We can reuse the variable by adding it as a parameter in the display function. Consider the following

Example

script.py
from flask import *  
app = Flask(__name__)  
@app.route('/admin')
ef admin():
return 'admin'  @app.route('/librarion')  
def librarion():  
return 'librarion'  
@app.route('/student')  
def student():  
return 'student'  
@app.route('/user/<name>')  
def user(name):  
if name == 'admin':  
return redirect(url_for('admin'))  
if name == 'librarion':  
return redirect(url_for('librarion'))  
if name == 'student':  
return redirect(url_for('student'))  
if __name__ =='__main__':  
app.run(debug = True) 

 The  above script has a function user(name), which accepts a value to its argument from the URL address.

The User()  function then checks if an argument received matches ‘admin’ or not. If it matches, the application is redirect to the hello admin() function using url for(), otherwise to the hello guest() function passing the received argument as guest parameter to it.

Flask URL Building

For example, the URL http://localhost:5000/user/admin is redirected to the URL http://localhost:5000/admin, the URL localhost:5000/user/librarion, is redirected to the URL http://localhost:5000/librarion, the URL http://localhost:5000/user/student is redirected to the URL http://localhost/student.

Advantages of  dynamic  URL binding

  • Hard coding of the URLs is avoided
  • Using Dynamic binding,  it  can be  automatically modify the URLs instead of recalling the hard-coded URLs that have been changed manually.
  • URL building handles both the Unicode data and escaping of special characters   in a very transparent manner
  • Generated paths are always absolute in general and, avoiding unexpected behavior of relative paths in browsers.
  • If your application is placed outside the URL root, for example, in /application instead of /, url_for() correctly handles it for you.