Bird
Raised Fist0
Flaskframework~20 mins

Repository pattern for data access in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Repository Mastery in Flask
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does the repository pattern improve Flask app data access?

Consider a Flask app using the repository pattern for data access. What is the main benefit of using this pattern?

AIt forces all database queries to be written inline in the route functions.
BIt separates data access logic from business logic, making code easier to maintain and test.
CIt removes the need for any database connection or ORM.
DIt automatically caches all data without extra code.
Attempts:
2 left
💡 Hint

Think about how separating concerns helps in coding.

📝 Syntax
intermediate
1:30remaining
Identify the correct repository method signature in Flask

Which of the following method signatures correctly defines a repository method to fetch a user by ID in Flask?

Flask
class UserRepository:
    def get_user_by_id(self, user_id):
        pass
Adef get_user_by_id(self, user_id):
Bdef getUserById(user_id):
Cdef get_user_by_id(userId):
Ddef get_user_by_id():
Attempts:
2 left
💡 Hint

Remember Python method conventions and parameters.

❓ state_output
advanced
2:00remaining
What is the output of this Flask repository usage?

Given the repository and Flask route below, what will be the JSON response when accessing /user/2?

Flask
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
A{"name": "Bob"}
B500 Internal Server Error
C{"error": "User not found"}
D{"name": "Alice"}
Attempts:
2 left
💡 Hint

Check the user ID passed and the repository data.

🔧 Debug
advanced
2:00remaining
Why does this Flask repository code raise an error?

Examine the code below. Why does calling repo.get_user_by_id(1) raise an error?

Flask
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)
AThe method call passes an argument but method expects none, causing ValueError.
BThe users dictionary is empty, so KeyError occurs.
CMethod get_user_by_id is missing 'self' parameter, causing a TypeError.
DThe class UserRepository is not instantiated before calling the method.
Attempts:
2 left
💡 Hint

Check method definitions inside classes.

🧠 Conceptual
expert
2:30remaining
Which statement best describes the repository pattern's role in Flask apps?

Choose the statement that best explains how the repository pattern benefits Flask applications in managing data access.

AIt automatically generates REST API endpoints for all database tables.
BIt requires all data queries to be written directly in Flask route functions for speed.
CIt eliminates the need for any ORM or database driver in the app.
DIt abstracts data storage details, allowing the app to switch databases without changing business logic.
Attempts:
2 left
💡 Hint

Think about flexibility and separation of concerns.

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

  1. 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.
  2. 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.
  3. Final Answer:

    To separate data access logic from business logic -> Option D
  4. 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

  1. Step 1: Check method signature in a class

    Repository methods inside a class must have self as the first parameter.
  2. Step 2: Verify correct SQLAlchemy query syntax

    To get all records, use User.query.all(). Other options use incorrect method names or miss self.
  3. Final Answer:

    def get_all_users(self): return User.query.all() -> Option B
  4. Quick Check:

    Method with self + User.query.all() = correct [OK]
Hint: Repository methods need self and correct query syntax [OK]
Common Mistakes:
  • Omitting self parameter in method
  • Using wrong query method like User.all()
  • Using User.query.get_all() which doesn't exist
3. Given this repository method in Flask:
def get_user_by_id(self, user_id):
    return User.query.filter_by(id=user_id).first()

What will repo.get_user_by_id(5) return if no user with ID 5 exists?
medium
A. None
B. Raises an exception
C. An empty list []
D. A User object with id 5

Solution

  1. Step 1: Understand SQLAlchemy filter_by().first() behavior

    The first() method returns the first matching record or None if no match is found.
  2. Step 2: Apply to user_id 5 with no matching user

    Since no user with ID 5 exists, the method returns None, not a list or exception.
  3. Final Answer:

    None -> Option A
  4. Quick Check:

    filter_by().first() returns None if no match [OK]
Hint: filter_by().first() returns None if no record found [OK]
Common Mistakes:
  • Expecting an empty list instead of None
  • Thinking it raises an exception
  • Assuming it returns a dummy User object
4. You wrote this repository method:
def add_user(self, user):
    db.session.add(user)
    db.session.commit

What is the error here?
medium
A. Missing parentheses after commit method call
B. db.session.add should be db.add
C. user parameter should be a dictionary, not an object
D. commit should be called before add

Solution

  1. Step 1: Check method calls on db.session

    The commit method must be called with parentheses: commit().
  2. Step 2: Identify the missing parentheses error

    Without parentheses, commit is just a reference, so changes are not saved.
  3. Final Answer:

    Missing parentheses after commit method call -> Option A
  4. 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

  1. Step 1: Understand filtering by string suffix in SQLAlchemy

    To filter emails ending with a string, use filter(User.email.endswith(...)).
  2. 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.
  3. Final Answer:

    def get_example_users(self): return User.query.filter(User.email.endswith('@example.com')).all() -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard