Performance: Route decorator (@app.route)
This affects server response routing speed and how quickly the correct view function is found and executed for a web request.
from flask import Flask, Blueprint app = Flask(__name__) user_bp = Blueprint('user', __name__, url_prefix='/user') @user_bp.route('/<username>') def user_profile(username): # shared logic factored out ... @user_bp.route('/<username>/settings') def user_settings(username): ... app.register_blueprint(user_bp)
from flask import Flask app = Flask(__name__) @app.route('/user/<username>') def user_profile(username): # complex logic inside route ... @app.route('/user/<username>/settings') def user_settings(username): # duplicated code in routes ...
| Pattern | Routing Lookup Cost | Server CPU Load | Code Maintainability | Verdict |
|---|---|---|---|---|
| Many similar routes with duplicated logic | High (linear with route count) | High | Low | [X] Bad |
| Grouped routes using Blueprints | Low (organized lookup) | Low | High | [OK] Good |
@app.route decorator do in a Flask application?@app.route is used to link a URL path to a function in Flask./home in Flask?@app.route('/home') placed immediately before a function definition./user/42 given this Flask code?@app.route('/user/<int:id>')
def show_user(id):
return f"User ID is {id}"/user/<int:id> captures an integer from the URL and passes it as the argument id to the function.id value inserted using an f-string.@app.route('/hello')
def hello():
print('Hello World')
return 'Hello!'print and return are not indented under def hello():./profile/john and returns Hello, john!. Which code correctly achieves this?username as a string variable using <username> in the URL.username as a parameter and return the greeting using an f-string.Pass the test and this pattern moves unknown