📖 Scenario: You are building a simple Flask web app to manage books in a library. To keep your code clean and organized, you want to separate how you access data from the rest of your app. This is where the repository pattern helps.Think of the repository as a friendly librarian who knows exactly how to find, add, or remove books from the library database. Your app will ask the librarian instead of searching the shelves directly.
🎯 Goal: Build a Flask app that uses the repository pattern to manage book data. You will create a list of books, set up a repository class to handle data access, implement methods to get all books and add a new book, and finally connect this repository to a Flask route to display the books.
📋 What You'll Learn
Create a list of book dictionaries with exact titles and authors
Create a repository class called BookRepository to manage book data
Implement a method get_all_books that returns all books
Implement a method add_book that adds a new book to the list
Create a Flask route /books that uses the repository to show all books
💡 Why This Matters
🌍 Real World
The repository pattern helps keep your Flask app organized by separating data access from business logic. This makes your code easier to maintain and test.
💼 Career
Many companies use the repository pattern in web development to build scalable and clean applications. Knowing this pattern is valuable for backend and full-stack developer roles.
Progress0 / 4 steps
1
DATA SETUP: Create the initial book list
Create a list called books with these exact dictionaries: {'title': '1984', 'author': 'George Orwell'}, {'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'}, and {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'}.
Flask
Hint
Remember to create a list named books with exactly three dictionaries inside it.
2
CONFIGURATION: Define the BookRepository class
Create a class called BookRepository with an __init__ method that takes a parameter books and assigns it to self.books.
Flask
Hint
Define a class named BookRepository with an __init__ method that stores the passed books list in self.books.
3
CORE LOGIC: Add methods to get and add books
Inside the BookRepository class, add a method get_all_books that returns self.books. Also add a method add_book that takes a parameter book and appends it to self.books.
Flask
Hint
Define two methods inside BookRepository: one to return all books, and one to add a new book to the list.
4
COMPLETION: Create Flask app and route using the repository
Import Flask and create an app instance called app. Instantiate BookRepository with the books list as repo. Create a route /books that returns a string listing all book titles from repo.get_all_books() separated by commas.
Flask
Hint
Import Flask, create the app, instantiate the repository, and define a route that returns all book titles joined by commas.
Practice
(1/5)
1. What is the main purpose of using the Repository pattern in a Flask application?
easy
A. To create HTML templates for the frontend
B. To speed up the Flask server response time
C. To handle user authentication automatically
D. To separate data access logic from business logic
Solution
Step 1: Understand the role of repository pattern
The repository pattern is designed to separate how data is accessed from how it is used in the app logic.
Step 2: Identify the correct purpose in Flask context
In Flask, this means keeping database queries inside repository classes, so the rest of the app doesn't need to know database details.
Final Answer:
To separate data access logic from business logic -> Option D
Quick Check:
Repository pattern = separation of concerns [OK]
Hint: Repository pattern means separate data from app logic [OK]
Common Mistakes:
Thinking it speeds up server response
Confusing it with authentication handling
Assuming it creates frontend templates
2. Which of the following is the correct way to define a repository class method to get all users in Flask?
easy
A. def get_all_users(): return User.query.all()
B. def get_all_users(self): return User.query.all()
C. def get_all_users(self): return User.all()
D. def get_all_users(self): return User.query.get_all()
Solution
Step 1: Check method signature in a class
Repository methods inside a class must have self as the first parameter.
Step 2: Verify correct SQLAlchemy query syntax
To get all records, use User.query.all(). Other options use incorrect method names or miss self.
Final Answer:
def get_all_users(self): return User.query.all() -> Option B
Quick Check:
Method with self + User.query.all() = correct [OK]
Hint: Repository methods need self and correct query syntax [OK]
C. user parameter should be a dictionary, not an object
D. commit should be called before add
Solution
Step 1: Check method calls on db.session
The commit method must be called with parentheses: commit().
Step 2: Identify the missing parentheses error
Without parentheses, commit is just a reference, so changes are not saved.
Final Answer:
Missing parentheses after commit method call -> Option A
Quick Check:
commit() needs parentheses to execute [OK]
Hint: Always call commit() with parentheses [OK]
Common Mistakes:
Forgetting parentheses on commit
Using db.add instead of db.session.add
Calling commit before add
5. You want to implement a repository method that returns all users whose email ends with '@example.com'. Which of these is the best way to write it using SQLAlchemy in Flask?
hard
A. def get_example_users(self): return User.query.filter(User.email.contains('@example.com')).first()
B. def get_example_users(self): return User.query.filter_by(email='@example.com').all()
C. def get_example_users(self): return User.query.filter(User.email.endswith('@example.com')).all()
D. def get_example_users(self): return User.query.filter(User.email == '@example.com').all()
Solution
Step 1: Understand filtering by string suffix in SQLAlchemy
To filter emails ending with a string, use filter(User.email.endswith(...)).
Step 2: Check each option's correctness
def get_example_users(self): return User.query.filter(User.email.endswith('@example.com')).all() uses 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.
Final Answer:
def get_example_users(self): return User.query.filter(User.email.endswith('@example.com')).all() -> Option C
Quick Check:
Use endswith() + all() for suffix filtering [OK]
Hint: Use endswith() for suffix filtering in queries [OK]
Common Mistakes:
Using filter_by for partial matches
Using contains but returning only first result
Using equality operator instead of endswith
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.