Generating urls in Python flask

share link

by vsasikalabe dot icon Updated: Mar 8, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Mapping the URLs to a specific function is called App Routing. This is the logic for that URL. Users will easily remember the URLs by making them meaningful and making navigation simpler. For example, The URL ("/") is linked with the root URL. The __name__ is a special built-in variable. It evaluates the name of the current module. 

In Flask, the route() decorator is used to bind a URL to a function. As a result, when the URL is typed in the browser, the function is executed, or the corresponding output will get displayed. Here, the URL '/user/username' rule is bound to the username function. As an outcome, if a user visits http://localhost:5000/ URL, the output of the username will be rendered in the browser. 

Benefits of the Dynamic URL Building 

  • It avoids hard coding of the URLs. 
  • Instead of remembering the manually changed URLs, we can change the URLs dynamically. 
  • URL building handles Unicode data transparently and the escape of special characters. 
  • The generated paths are always absolute. It avoids unexpected behavior of paths in browsers. 

Here is an example of how to generate URLs using Python Flask: