We’ve seen how the route()
decorator can be used to bind one or more static URLs to a view function. But what if we want to handle a set of URLs that may be constantly changing? Let’s take a look at how we can use variable rules to allow for dynamic URLs.
When specifying the URL to bind to a view function, we have the option of making any section of the path between the slashes (/
) variable by indicating <variable_name>
. These variable parts will then be passed to the view function as arguments. For example:
@app.route('/orders/<user_name>/<int:order_id>') def orders(user_name, order_id): return f'<p>Fetching order #{order_id} for {user_name}.</p>'
Now, URLs like '/orders/john/1'
and '/orders/jane/8'
can all be handled by the orders()
function.
Note that we can also optionally enforce the type of the variable being accepted using the syntax: <converter:variable_name>
. The possible converter types are:
string | accepts any text without a slash (default) |
---|---|
int | accepts positive integers |
float | accepts positive floating point values |
path | like string but also accepts slashes |
uuid | accepts UUID strings |
Instructions
Update the reporter
endpoint to handle requests from individual reporter pages whose URL path follows the pattern '/reporter/#'
.
Add a variable section called reporter_id
to the URL passed to the route()
decorator. Use a converter to specify that the variable part must be a positive integer.
Next, update the reporter()
function to take a parameter called reporter_id
. In the function body, modify the <h2>
heading to read Reporter # Bio
, where #
is the reporter_id
.
Run app.py. Try visiting various reporter pages such as https://localhost/reporter/1 or https://localhost/reporter/1000!