Performance: Repository pattern for data access
This pattern affects how data is fetched and managed, impacting server response time and client perceived loading speed.
class UserRepository: def __init__(self): self.cache = {} def get_user(self, user_id): if user_id not in self.cache: self.cache[user_id] = User.query.filter_by(id=user_id).first() return self.cache[user_id] class UserService: def __init__(self, repo): self.repo = repo def get_user_name(self, user_id): return self.repo.get_user(user_id).name def get_user_email(self, user_id): return self.repo.get_user(user_id).email
class UserService: def get_user_name(self, user_id): return User.query.filter_by(id=user_id).first().name def get_user_email(self, user_id): return User.query.filter_by(id=user_id).first().email
| Pattern | Database Queries | Server Response Time | Client Load Impact | Verdict |
|---|---|---|---|---|
| Direct multiple queries | Multiple per user | High | Slower LCP | [X] Bad |
| Repository with caching | Single per user | Low | Faster LCP | [OK] Good |
Repository pattern in a Flask application?self as the first parameter.User.query.all(). Other options use incorrect method names or miss self.def get_user_by_id(self, user_id):
return User.query.filter_by(id=user_id).first()repo.get_user_by_id(5) return if no user with ID 5 exists?first() method returns the first matching record or None if no match is found.None, not a list or exception.def add_user(self, user):
db.session.add(user)
db.session.commitcommit method must be called with parentheses: commit().commit is just a reference, so changes are not saved.filter(User.email.endswith(...)).endswith and all() to get all matches, which is correct. def get_example_users(self): return User.query.filter_by(email='@example.com').all() uses filter_by with exact match, not suffix. def get_example_users(self): return User.query.filter(User.email.contains('@example.com')).first() uses contains but returns only first match. def get_example_users(self): return User.query.filter(User.email == '@example.com').all() uses equality check, not suffix.Pass the test and this pattern moves unknown