Bird
Raised Fist0
Flaskframework~20 mins

Service layer pattern in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Service Layer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask service layer call?

Consider a Flask app using a service layer to fetch user data. What will be printed when calling print(user_service.get_user_name(2))?

Flask
class UserService:
    def __init__(self):
        self.users = {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

    def get_user_name(self, user_id):
        return self.users.get(user_id, 'Unknown')

user_service = UserService()
print(user_service.get_user_name(2))
AAlice
BBob
CUnknown
DCharlie
Attempts:
2 left
💡 Hint

Look at the dictionary key used in the get_user_name call.

❓ state_output
intermediate
2:00remaining
What is the state of the service after adding a new user?

After running user_service.add_user(4, 'Diana'), what will user_service.users contain?

Flask
class UserService:
    def __init__(self):
        self.users = {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

    def add_user(self, user_id, name):
        self.users[user_id] = name

user_service = UserService()
user_service.add_user(4, 'Diana')
A{1: 'Alice', 2: 'Bob', 3: 'Charlie'}
B{}
C{4: 'Diana'}
D{1: 'Alice', 2: 'Bob', 3: 'Charlie', 4: 'Diana'}
Attempts:
2 left
💡 Hint

Adding a user updates the users dictionary.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a Flask service method to delete a user?

Choose the correct method to remove a user by user_id from the users dictionary in the service layer.

Flask
class UserService:
    def __init__(self):
        self.users = {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

    def delete_user(self, user_id):
        # method to remove user
        pass
A
def delete_user(self, user_id):
    self.users.pop(user_id, None)
B
def delete_user(self, user_id):
    self.users.remove(user_id)
C
def delete_user(self, user_id):
    del self.users[user_id]
D
def delete_user(self, user_id):
    self.users.delete(user_id)
Attempts:
2 left
💡 Hint

Use a dictionary method that safely removes a key without error if missing.

🔧 Debug
advanced
2:00remaining
Why does this Flask service method raise a KeyError?

Given this service method, why does calling get_user_name(5) raise a KeyError?

Flask
class UserService:
    def __init__(self):
        self.users = {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

    def get_user_name(self, user_id):
        return self.users[user_id]

user_service = UserService()
user_service.get_user_name(5)
ABecause the method should use self.users.get(user_id) instead of self.users[user_id]
BBecause the users dictionary is empty
CBecause user_id 5 does not exist in the users dictionary and direct access raises KeyError
DBecause the UserService class is missing an __init__ method
Attempts:
2 left
💡 Hint

Accessing a missing key in a dictionary directly causes an error.

🧠 Conceptual
expert
2:00remaining
What is the main benefit of using a service layer in a Flask app?

Choose the best explanation for why a service layer is used in Flask applications.

AIt separates business logic from route handlers, making code easier to maintain and test
BIt automatically generates HTML templates for the app
CIt replaces the need for a database by storing data in memory
DIt handles user authentication and authorization automatically
Attempts:
2 left
💡 Hint

Think about code organization and responsibilities.

Practice

(1/5)
1. What is the main purpose of using a service layer in a Flask application?
easy
A. To serve static files like images and CSS
B. To separate business logic from route handlers for better organization
C. To handle database migrations automatically
D. To manage user sessions and cookies

Solution

  1. Step 1: Understand the role of service layer

    The service layer is designed to hold business logic separate from Flask routes, making code cleaner and easier to maintain.
  2. Step 2: Compare with other options

    Handling migrations, serving static files, and managing sessions are not the service layer's responsibilities.
  3. Final Answer:

    To separate business logic from route handlers for better organization -> Option B
  4. Quick Check:

    Service layer = separates business logic [OK]
Hint: Service layer = business logic outside routes [OK]
Common Mistakes:
  • Confusing service layer with database or session management
  • Thinking service layer serves static files
  • Assuming service layer handles HTTP requests directly
2. Which of the following is the correct way to call a service function get_user_by_id inside a Flask route?
easy
A. user = get_user_by_id(id)
B. user = service->get_user_by_id(id)
C. user = service.get_user_by_id(id)
D. user = get_user_by_id.service(id)

Solution

  1. Step 1: Understand typical service layer usage

    Service functions are usually grouped in a service object or module, so calling service.get_user_by_id(id) is correct.
  2. Step 2: Identify syntax errors in other options

    user = get_user_by_id(id) misses the service prefix, B uses invalid arrow syntax (->) for Python, C uses wrong dot notation.
  3. Final Answer:

    user = service.get_user_by_id(id) -> Option C
  4. Quick Check:

    Call service function with dot notation [OK]
Hint: Call service functions as service.function(args) [OK]
Common Mistakes:
  • Calling service functions without service prefix
  • Using invalid syntax like arrows (->)
  • Misplacing dot notation
3. Given this Flask route and service layer code, what will be the output when accessing /user/2 if user with ID 2 exists?
from flask import Flask, jsonify
app = Flask(__name__)

class UserService:
    def get_user_by_id(self, user_id):
        users = {1: 'Alice', 2: 'Bob'}
        return users.get(user_id, None)

service = UserService()

@app.route('/user/<int:user_id>')
def user(user_id):
    user_name = service.get_user_by_id(user_id)
    if user_name:
        return jsonify({'user': user_name})
    else:
        return jsonify({'error': 'User not found'}), 404
medium
A. {"error": "User not found"}
B. Server error due to missing user
C. 404 Not Found error without JSON
D. {"user": "Bob"}

Solution

  1. Step 1: Check user existence in service

    User with ID 2 exists in the dictionary as 'Bob', so get_user_by_id(2) returns 'Bob'.
  2. Step 2: Analyze route response

    Since user_name is truthy, route returns JSON with {'user': 'Bob'} and status 200.
  3. Final Answer:

    {"user": "Bob"} -> Option D
  4. Quick Check:

    User found returns JSON with user name [OK]
Hint: If user exists, route returns JSON with user name [OK]
Common Mistakes:
  • Assuming 404 error when user exists
  • Confusing JSON error message with missing user
  • Thinking server error occurs without exception
4. Identify the error in this Flask route using a service layer:
from flask import Flask, jsonify
app = Flask(__name__)

class UserService:
    def get_user(self, user_id):
        return None

service = UserService()

@app.route('/user/<int:user_id>')
def user(user_id):
    user = service.get_user(user_id)
    if user:
        return jsonify({'user': user})
    else:
        return jsonify({'error': 'User not found'})
medium
A. The service method always returns None, so user is never found
B. The route decorator syntax is incorrect
C. Missing return statement in the else block
D. Flask app is not instantiated properly

Solution

  1. Step 1: Analyze service method return value

    The get_user method always returns None, so user is always None in the route.
  2. Step 2: Understand route behavior

    Because user is None, the route always returns the error JSON, meaning no user is ever found.
  3. Final Answer:

    The service method always returns None, so user is never found -> Option A
  4. Quick Check:

    Service returns None means no user found [OK]
Hint: Check service method return values carefully [OK]
Common Mistakes:
  • Assuming route decorator is wrong
  • Missing return in else block (actually present)
  • Thinking Flask app is not created properly
5. You want to add a new service method create_user that saves a user and returns the new user ID. Which approach best follows the service layer pattern in Flask?
medium
A. Add create_user method in service class and call it from route
B. Write database code directly in the route
C. Put user creation logic in app initialization
D. Use global variable in route without service

Solution

  1. Step 1: Recall service layer purpose

    The service layer should contain business logic like user creation, keeping routes simple and clean.
  2. Step 2: Evaluate options

    Add create_user method in service class and call it from route correctly adds create_user to the service class and calls it from the route, following the pattern.
  3. Final Answer:

    Add create_user method in service class and call it from route -> Option A
  4. Quick Check:

    Business logic in service, routes call service [OK]
Hint: Put business logic in service, call from routes [OK]
Common Mistakes:
  • Putting logic directly in routes
  • Using global variables instead of service
  • Placing logic in app initialization
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