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__)  
def admin():  
    return 'admin'  
def librarion():  
    return 'librarion'  
def student():  
    return 'student'  
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)  


 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

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.