Understanding Flask Variable Rules

With Flask variable rules, you can create dynamic routes for your web applications.

You define variable rules in the route path by enclosing a section of the path with angle brackets “<>” and providing a variable name inside the brackets.

These variables can be used to generate personalized responses for your users.



Flask Variable Rules

Flask variable rules enable the creation of dynamic URLs by allowing the incorporation of one or more variables that can facilitate the transfer of information between pages. A URL such as /welcome/17 could be established, with 17 serving as a variable that represents a user ID.

To define variable rules in Flask, angled brackets (<>) are utilized in the route definition, with the variable’s name specified within the brackets.

For instance, a route accepting a user ID variable could be established by defining a route in the following manner:

from flask import Flask

app = Flask(__name__)

@app.route('/greetings/<username>')

def display_name(username):

    return f'Heyy {username} how are you?'

if __name__ == '__main__':

    app.run(debug = True)

You can save the above script provided as “Greetings.py” and execute it within the Python shell. Then, proceed to open a web browser and entering the following URL: http://localhost:5000/greetings/Developer.

The browser will render the result that follows.

Flask Variable Rules output

Apart from the default string variable segment, rules can be generated utilizing the converters listed below.

Sr.No.Overview
1int

Supports integers

2float

To express a numerical value with a fractional component.

3path

Allows forward slashes to be utilized as the character that separates directories.

All of the constructors are utilized in the code below.

from flask import Flask

app = Flask(__name__)

@app.route('/intnum/<int:num>')

def intNum(num):

    return f'Integer Number is: {num}'

@app.route('/floatnum/<float:num>')

def floatNum(num):

    return f'Float Number is: {num}'

if __name__ == '__main__':

    app.run(debug = True)

Display the above code with format specifiers:

from flask import Flask

app = Flask(__name__)

@app.route('/intnum/<int:num>')

def intNum(num):

    return 'Integer Number is: %d' %num

@app.route('/floatnum/<float:num>')

def floatNum(num):

    return 'Float Number is: %f' %num

if __name__ == '__main__':

    app.run(debug = True)

Execute the aforementioned code in the Python Shell, then open a web browser and navigate to the URL http://localhost:5000/intnum/28. This will pass the number 28 as an argument to the intNum() function, and the response will be rendered in the browser.

Integer Number is: 28

Type the given URL, http://localhost:5000/floatnum/91.25, into the browser’s address bar. This will pass the floating point number 91.25 as an argument to the floatNum() function. The resulting output will then be visible in the browser window.

Float Number is: 91.250000

Flask’s URL routing system is built on top of Werkzeug’s routing module.

This guarantees that the URLs generated are distinct and follow the standards established by Apache.

Take a look at the following script to determine the routing rules:

from flask import Flask

app = Flask(__name__)

@app.route('/mrexamples/')

def mrx():

    return 'Hello developers welcome to mrexamples'

@app.route('/cleverbot2')

def chatbot():

    return 'This is a chat bot. Here you can ask anything you want'

if __name__ == '__main__':

    app.run(debug = True)

In the following code, render the difference and sum of the numbers in the browser:

from flask import Flask

app = Flask(__name__)

@app.route('/add')

def add():

    return f'7 + 10 = {7+10}'

@app.route('/difference/')

def subtract():

    return f'10 - 7 = {10-7}'

if __name__ == '__main__':

    app.run(debug = True)

While both rules may seem alike, the second one uses a trailing slash, making it the authoritative URL. Therefore, accessing either /difference or /difference/ will give an identical response. However, attempting to access /add/ through the first rule will result in a 404 Not Found error page.

Example Explanation

  • The above code example showcases a Flask web application with two routes.
  • These routes are defined using the @app.route decorator.
  • The first route, /add, calls a function called add which adds two numbers (7 and 10) and displays the result as a string.
  • When the user visits the URL http://localhost:5000/add, the add function is executed and displays “7 + 10 = 17” in the browser.
  • The second route, /difference/, calls a function called subtract which subtracts 7 from 10 and displays the result as a string.
  • This route has a trailing slash, making it the canonical URL, so /difference and /difference/ will execute the same function.
  • When the user visits the URL http://localhost:5000/difference or http://localhost:5000/difference/, the subtract function is executed and displays “10 – 7 = 3” in the browser.
  • Finally, the if name == ‘__main__’: block starts the Flask application in debug mode on the local host.

Benefits

  • Flask variable rules enable dynamic URL routing that allows developers to define a single URL pattern that can match multiple unique URLs.
  • Using Flask variable rules, developers can create clean and readable URLs that can improve the user experience and make it easier for search engines to index web pages.
  • Flask variable rules can be used to extract data from the URL and use it in the application logic, such as extracting a user ID from the URL to display the appropriate user information.
  • Flask variable rules can also improve error handling in web applications by redirecting users to more appropriate pages or displaying error messages when users enter incorrect URLs.

Conclusion

To work with variables in Flask, it is important to adhere to a set of guidelines to guarantee the smooth and effective functioning of your application. These guidelines encompass the correct definition of variables, their proper transmission to templates, and ensuring that they are type-safe. Additionally, following the syntax and conventions for variable use in Flask is vital to ensure the readability and maintainability of your code. By adhering to these guidelines, you can construct dynamic and responsive web pages that utilize variables to create personalized and captivating user experiences. In summary, comprehending the regulations for handling variables in Flask is critical for developers seeking to create robust web applications with this widely used Python framework.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *