Complete the code to create a basic Flask app that runs on the default port.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, World!' if __name__ == '__main__': app.run([1])
Setting debug=False runs the Flask app in normal mode, which is important for performance in production.
Complete the code to add caching to improve Flask app performance.
from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': '[1]'}) @app.route('/') @cache.cached(timeout=60) def home(): return 'Cached response!' if __name__ == '__main__': app.run(debug=False)
The simple cache type uses in-memory caching which is easy to set up and improves performance for small apps.
Fix the error in the code to correctly measure request processing time in Flask.
from flask import Flask, g, request import time app = Flask(__name__) @app.before_request def start_timer(): g.start = time.time() @app.after_request def log_time(response): duration = time.time() - [1] print(f'Request took {duration:.4f} seconds') return response @app.route('/') def home(): return 'Hello!' if __name__ == '__main__': app.run(debug=False)
The start time is stored in g.start, so we must use that to calculate duration.
Fill both blanks to create a route that accepts a dynamic user ID and returns it.
from flask import Flask app = Flask(__name__) @app.route('/user/[1]') def user_profile([2]): return f'User ID is {user_id}' if __name__ == '__main__': app.run(debug=False)
The route uses <int:user_id> to capture an integer user ID, and the function parameter must match that name user_id.
Fill all three blanks to create a dictionary comprehension that maps user IDs to their names for users with IDs greater than 10.
users = {1: 'Alice', 12: 'Bob', 15: 'Charlie', 7: 'Diana'}
filtered_users = { [1]: [2] for [3] in users if [1] > 10 }The comprehension iterates over user_id in users, mapping user_id to users[user_id] for IDs greater than 10.