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))?
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))
Look at the dictionary key used in the get_user_name call.
The get_user_name method returns the value for key 2, which is 'Bob'.
After running user_service.add_user(4, 'Diana'), what will user_service.users contain?
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')
Adding a user updates the users dictionary.
The add_user method adds a new key-value pair to the existing dictionary.
Choose the correct method to remove a user by user_id from the users dictionary in the service layer.
class UserService: def __init__(self): self.users = {1: 'Alice', 2: 'Bob', 3: 'Charlie'} def delete_user(self, user_id): # method to remove user pass
Use a dictionary method that safely removes a key without error if missing.
pop(key, None) removes the key if present without raising an error. del raises an error if key missing. remove and delete are invalid for dict.
Given this service method, why does calling get_user_name(5) raise a KeyError?
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)
Accessing a missing key in a dictionary directly causes an error.
Direct dictionary access with a missing key raises KeyError. Using get() returns None or default instead.
Choose the best explanation for why a service layer is used in Flask applications.
Think about code organization and responsibilities.
The service layer keeps business logic separate from routes, improving maintainability and testability. It does not generate templates, replace databases, or handle auth automatically.