Consider a Flask app using the repository pattern for data access. What is the main benefit of using this pattern?
Think about how separating concerns helps in coding.
The repository pattern creates a clear layer between how data is fetched or saved and how the app uses that data. This separation makes the code cleaner and easier to change or test.
Which of the following method signatures correctly defines a repository method to fetch a user by ID in Flask?
class UserRepository: def get_user_by_id(self, user_id): pass
Remember Python method conventions and parameters.
In Python classes, methods must have 'self' as the first parameter. The method name should be snake_case. The parameter name should be descriptive and consistent.
Given the repository and Flask route below, what will be the JSON response when accessing /user/2?
class UserRepository: def __init__(self): self.users = {1: {'name': 'Alice'}, 2: {'name': 'Bob'}} def get_user_by_id(self, user_id): return self.users.get(user_id, None) from flask import Flask, jsonify app = Flask(__name__) repo = UserRepository() @app.route('/user/<int:user_id>') def get_user(user_id): user = repo.get_user_by_id(user_id) if user: return jsonify(user) else: return jsonify({'error': 'User not found'}), 404
Check the user ID passed and the repository data.
The repository has user ID 2 mapped to Bob. The route returns the user data as JSON if found.
Examine the code below. Why does calling repo.get_user_by_id(1) raise an error?
class UserRepository: def __init__(self): self.users = {1: {'name': 'Alice'}} def get_user_by_id(): return self.users.get(1) repo = UserRepository() repo.get_user_by_id(1)
Check method definitions inside classes.
Instance methods must have 'self' as the first parameter. Without it, Python raises a TypeError when calling with an argument.
Choose the statement that best explains how the repository pattern benefits Flask applications in managing data access.
Think about flexibility and separation of concerns.
The repository pattern hides how data is stored or retrieved. This lets developers change the database or data source without rewriting the app's core logic.