Performance: Why routing is Flask's core
Routing affects how quickly the server matches URLs to code, impacting response time and user experience.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Home page' @app.route('/about') def about(): return 'About page' @app.route('/user/<username>') def user_profile(username): return f'Profile of {username}'
from flask import Flask app = Flask(__name__) @app.route('/<path:any_path>') def catch_all(any_path): # Single catch-all route handling all URLs return 'Handled by catch-all'
| Pattern | Routing Matching Cost | Response Delay | Server Load | Verdict |
|---|---|---|---|---|
| Single catch-all route | High (checks all URLs in one handler) | Increased delay for all requests | Higher due to inefficient matching | [X] Bad |
| Specific routes per URL | Low (direct match) | Minimal delay | Lower due to efficient matching | [OK] Good |
/user/42 in this Flask app?@app.route('/user/<int:id>')
def show_user(id):
return f'User ID is {id}'@app.route('/hello')
def hello():
print('Hello World')
return 'Hello!'Pass the test and this pattern moves unknown