Last Updated : 19 Mar, 2025
Flask variable rules allow us to create dynamic URLs by defining variable parts within the route. This makes it possible to capture values from the URL and pass them to view functions.
Variable RulesThe following converters are available in Flask-Variable Rules:
In this code we will create a basic flask app in which we will return a simple welcome line. Run the app by executing this command in the terminal - "python app.py".
Python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def msg():
return "Welcome To The GreeksForGreeks"
# we run code in debug mode
app.run(debug=True)
Output:
127.0.0.1:5000 String Variable in FlaskIn this code, we will define a function that handles a dynamic string variable in the URL.
Python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def msg():
return "Welcome"
# We defined string function
@app.route('/vstring/<name>')
def string(name):
return "My Name is %s" % name
# we run app debugging mode
app.run(debug=True)
Output :
String VariableExplanation:
To understand how integer variables work in flask let's create a function that handles integers since Flask doesn't define it by default. Finally, we return the integer value and run the app. To access the integer page, we include the function name and an integer in the URL.
Python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def msg():
return "Welcome"
# define int function
@app.route('/vint/<int:age>')
def vint(age):
return "I am %d years old " % age
# we run our code in debug mode
app.run(debug=True)
Output:
Integer Variable FlaskExplanation:vint() function handles URLs with an integer parameter (<int:age>). It ensures only integers are accepted and returns a formatted string with the provided age.
Float Variable in FlaskTo demonstrate a float variable in Flask, we define a float function since Flask doesn’t define it by default. The function returns the float value, and we run the app using Flask run. To access the float page, we include the function name and a floating-point number in the URL.
Python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def msg():
return "Welcome"
# define float function
@app.route('/vfloat/<float:balance>')
def vfloat(balance):
return "My Account Balance %f" % balance
# we run our code in debugging mode
app.run(debug=True)
Output:
Float VariableExplanation:vfloat function handles URLs with a float value (e.g., /vfloat/100.50). It returns a formatted message displaying the float value.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4