Flask URL Building



 url_for() function

url_for() function

  • url_for() function - It is used to build a URL to the specific function dynamically. The first parameter is the name of the particular function, and then you can pass any number of keyword parameter corresponding to the variable part of the URL.

Sample code

from flask import *  
   app = Flask(__name__)  
  @app.route('/admin')  
def 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)  

Output

 Flask Url Building Output

For ex, 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.

URL Building

Benefits of the Dynamic URL Building

  • Avoids hard coding of the URLs.
  • Change the URLs dynamically instead of remembering the manually changed hard-coded URLs.
  • It handles the escaping of special characters and Unicode data transparently.
  • If your application is placed outside the URL root, url_for() properly handles that for you.
  • The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.

If you want to learn about Python Course , you can refer the following links Python Training in Chennai , Machine Learning Training in Chennai , Data Science Training in Chennai , Artificial Intelligence Training in Chennai



Related Searches to Flask URL Building