Flask by Example: Route Path Matching
Routing is the mechanism that maps URLs to specific functions in your application. Flask provides flexible routing capabilities, including variable rules and type converters.
Code
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
# 1. Static Route
@app.route('/')
def index():
return 'Index Page'
# 2. Variable Rules (String default)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'
# 3. Type Converters (Integer)
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {post_id}'
# 4. Path Converter (Accepts slashes)
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'
# 5. HTTP Methods
@app.route('/login', methods=['GET', 'POST'])
def login():
return 'Login Page'Explanation
Routing in Flask is handled via the @app.route decorator, which binds a URL pattern to a Python function. This mechanism allows you to define the entry points of your application cleanly and intuitively. By decorating a function, you tell Flask to execute that code whenever a user visits the matching URL.
Flask supports dynamic URL construction through variable rules (e.g., <variable_name>) and converters like int: or path:. These converters automatically validate the input data type, returning a 404 error if the format doesn't match, which simplifies your error handling logic significantly.
Security is paramount when handling user input from URLs. The use of escape() prevents Cross-Site Scripting (XSS) attacks by ensuring that any user-provided content rendered back to the browser is treated as text, not executable HTML or JavaScript.
Code Breakdown
@app.route('/'). This is the simplest route definition. It maps the root URL of the application to the index function.<username> captures a string from the URL. Flask passes this value to the show_user_profile function as the argument username.<int:post_id> uses a converter. If the user visits /post/abc, Flask will return a 404 Not Found error automatically because "abc" is not an integer. If valid, post_id is passed as a Python int.<path:subpath> is a special converter that matches the rest of the URL, including slashes. Standard string variables stop matching at the first slash.
