Flask App routing



  • It is used to map the specific URL function that is intended to perform some task. The output of that function is rendered on the webpage.
  • In Our first application, the URL ('/') is associated with the home function that returns a specific string displayed on the web page.
  • Here, You can reuse the variable by adding that as a parameter into the view function.

Sample Code

from flask import Flask  
app = Flask(__name__)  
 
@app.route('/home/<name>')  
def home(name):  
    return "hello,"+name;  
  
if __name__ =="__main__":  
    app.run(debug = True)  

Output

 Flask App Routing Output

Flask App Routing Output

  • The converter can be used in the URL to map the particular variable to the specified data type. For Ex, You can provide it integer or float like age.

Sample Code

from flask import Flask  
app = Flask(__name__)  
 
@app.route('/home/<int:age>')  
def home(age):  
    return "Age = %d"%age;  
  
if __name__ =="__main__":  
    app.run(debug = True)  

Output

 Output2

int or float

Converters

 Converter

App Routing Converter

  • These converters are used to convert the default string type to the associated data type.
    • string: Default
    • int: Convert the string to the integer
    • float: Convert the string to the float
    • path: It can accept the slashes given in the URL

Read Also

 Converter1

Converter1

add_url() Function

  • add_url() function is used to perform routing for the flask Web application.
 Add Url

Add Url

Syntax

add_url_rule(<url rule>, <endpoint>, <view function>)  

Sample code

from flask import Flask  
app = Flask(__name__)  
  
def about():  
    return "This is about page. ";  
  
app.add_url_rule("/about","about",about)  
  
if __name__ =="__main__":  
    app.run(debug = True)  

Output

 Output3

Output

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 App routing