Middle
Tell me about the Repository pattern and how you use it.
sobes.tech AI
Answer from AI
The Repository pattern serves as an abstraction between business logic and the data access layer. It encapsulates the logic for retrieving and saving data, allowing the data source (database, API, files) to be changed without modifying the rest of the code.
In Python, a repository class is usually created with methods like get_by_id(), add(), remove(), list(), etc. This simplifies testing (you can replace the repository with mocks) and improves code readability.
Example:
class UserRepository:
def __init__(self, db_session):
self.db = db_session
def get_by_id(self, user_id):
return self.db.query(User).filter(User.id == user_id).first()
def add(self, user):
self.db.add(user)
self.db.commit()
I use this pattern to separate business logic from database details and to facilitate support and extension of the application.