Routing & Dynamic URL Parameters
Routing is used to bind a URL to a Python function. Dynamic routes allow you to extract variables from the path segment dynamically.
1 Defining Routes & URL Converters
Python — app.py
from flask import Flask
app = Flask(__name__)
# Basic routing
@app.route("/about")
def about():
return "About Us"
# Dynamic routing with default string converter
@app.route("/user/<username>")
def show_user_profile(username):
return f"User Profile: {username}"
# Dynamic routing with specific type converters
@app.route("/post/<int:post_id>")
def show_post(post_id):
return f"Showing Post ID: {post_id}"
@app.route("/path/<path:subpath>")
def show_subpath(subpath):
return f"Subpath: {subpath}"
2 Allowed Converters
| Converter | Description |
|---|---|
string | Accepts any text without a slash (default) |
int | Accepts positive integers |
float | Accepts positive floating point values |
path | Accepts text with slashes (matches entire remaining path) |
uuid | Accepts UUID strings |
3 Code Challenge
Challenge: Write a route that accepts a float value
/temperature/<float:val> and returns a statement indicating whether it is above or below freezing (0.0 degrees).