Hi again :)
We'll be creating dynamic URL routes in an application.
In this article, I shall be discussing variable rules, converters and give an example using dynamic routing.
We've talked about routes and views and static routing where the rule
parameter of the route
decorator was a string.
@app.route("/about")
def learn():
return "All about Flask!"
In dynamic routing, the rule
parameter is not a constant string but a variable rule which is passed to the route()
.
What's a Variable Rule?
In Flask, variable rules are added inside the URL route using this syntax: variable_name
.
This variable_name
is then passed to the view function that's to be used.
Soooo...looks like I create new folders and virtual environments every time I blog because I usually delete the old folders, lol. I don't know if this is good practice though.
Anyway, here's the usual: if you're wondering how I got to this point, please check out this article.
Fast forward
"""An example application to demonstrate Variable Rules in Routing"""
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
"""View for the Home page of your website."""
return "This is your homepage :)"
@app.route("/<your_name>")
def greetings(your_name):
"""View function to greet the user by name."""
return "Welcome "+ your_name +"!"
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=3000)
Gives you:
Let's try something:
Adding /
+ your name
to the URL gives you another output :)
Cool right?
How does this work? You'll notice in our code above, in the second view function, greetings()
, we use the variable rule: /<your_name>
.
In this URL, the variable is your_name
. This variable is then passed as a parameter to the greetings()
function and then this variable is used to return a greeting to whoever's using it.
Converter
In the above example, the URL was used to extract the variable your_name
. This variable was then converted into a string and passed to the greetings()
function. It's the default behaviour of converters.
The data types they can convert are:
- Strings: by default
- int: for positive integers only
- float: for positive floating point numbers only
- path: for strings with slashes
- uuid: for UUID strings #UUID (Universally Unique Identifier) strings are used for identifying information that needs to be unique within a system or network. More on this here.
References:
- - - - - - -
Thank you for reading! See you in my next post :)