0
0
Flaskframework~30 mins

Service layer pattern in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Service Layer in Flask
📖 Scenario: You are creating a simple Flask web app to manage a list of books. You want to keep your code clean by separating the logic that handles book data from the web routes. This is done using a service layer.
🎯 Goal: Build a Flask app with a service layer that manages book data separately from the route handlers.
📋 What You'll Learn
Create a list of books as initial data
Add a configuration variable for minimum title length
Implement a service class with a method to get books with titles longer than the minimum length
Use the service class in a Flask route to display filtered books
💡 Why This Matters
🌍 Real World
Service layers help keep web apps organized by separating business logic from web routes, making code easier to maintain and test.
💼 Career
Understanding service layers is important for backend developers working with Flask or similar frameworks to build clean, scalable applications.
Progress0 / 4 steps
1
DATA SETUP: Create the initial book list
Create a list called books with these exact dictionaries: {'id': 1, 'title': 'Flask Basics'}, {'id': 2, 'title': 'Advanced Flask'}, and {'id': 3, 'title': 'Python Tips'}.
Flask
Need a hint?

Use a list with dictionaries inside. Each dictionary has keys 'id' and 'title'.

2
CONFIGURATION: Add minimum title length variable
Create a variable called MIN_TITLE_LENGTH and set it to 12.
Flask
Need a hint?

Just create a variable with the exact name and value.

3
CORE LOGIC: Implement the BookService class
Create a class called BookService with an __init__ method that takes books and min_length. Add a method called get_long_titles that returns a list of books with titles longer than min_length. Use a list comprehension with book['title'] and min_length.
Flask
Need a hint?

Use a class with an __init__ method to save books and min_length. Use a list comprehension in get_long_titles.

4
COMPLETION: Use BookService in a Flask route
Import Flask and create an app with app = Flask(__name__). Create a route @app.route('/books') with a function show_books. Inside it, create a BookService instance with books and MIN_TITLE_LENGTH. Return a string joining the titles from get_long_titles() separated by commas.
Flask
Need a hint?

Import Flask, create app, define route, create service instance, get filtered books, join titles, and return string.