Vertical Slice Architecture for an EPUB Reader App in Python
Vertical slice architecture is an approach where you build complete, end-to-end functionality for a narrow feature set rather than building horizontal layers (like all UI first, then all business logic). This is particularly useful for an EPUB reader app as it allows you to deliver working features incrementally.
Core Concepts of Vertical Slice Architecture
- Feature-based organization: Structure code around features rather than technical layers
- End-to-end implementation: Each slice contains all necessary components (UI, business logic, data access)
- Incremental delivery: Build one complete feature at a time
Applying Vertical Slice to an EPUB Reader
Let's break down how to implement an EPUB reader using vertical slices in Python.
1. Project Structure
epub_reader/
├── features/
│ ├── book_loading/
│ │ ├── __init__.py
│ │ ├── ui.py
│ │ ├── services.py
│ │ └── models.py
│ ├── chapter_navigation/
│ │ ├── __init__.py
│ │ ├── ui.py
│ │ ├── services.py
│ │ └── models.py
│ ├── bookmarking/
│ │ ├── __init__.py
│ │ ├── ui.py
│ │ ├── services.py
│ │ └── models.py
│ └── search/
│ ├── __init__.py
│ ├── ui.py
│ ├── services.py
│ └── models.py
├── shared/
│ ├── epub_parser.py
│ ├── storage.py
│ └── utils.py
└── main.py
2. Concrete Implementation Examples
Slice 1: Book Loading Feature
features/book_loading/models.py
from dataclasses import dataclass
from typing import List
@dataclass
class BookMetadata:
title: str
author: str
chapters: List[str]
cover_image: bytes = None
features/book_loading/services.py
from shared.epub_parser import EPUBParser
from .models import BookMetadata
class BookLoadingService:
def __init__(self, parser: EPUBParser):
self.parser = parser
def load_book(self, file_path: str) -> BookMetadata:
"""Load and parse an EPUB file"""
epub_data = self.parser.parse_epub(file_path)
return BookMetadata(
title=epub_data['title'],
author=epub_data['author'],
chapters=epub_data['chapters'],
cover_image=epub_data.get('cover_image')
)
features/book_loading/ui.py
import tkinter as tk
from tkinter import filedialog
from .services import BookLoadingService
class BookLoadingUI:
def __init__(self, root: tk.Tk, service: BookLoadingService):
self.root = root
self.service = service
self.setup_ui()
def setup_ui(self):
self.open_button = tk.Button(
self.root,
text="Open EPUB",
command=self.open_file_dialog
)
self.open_button.pack(pady=10)
def open_file_dialog(self):
file_path = filedialog.askopenfilename(
title="Select EPUB File",
filetypes=[("EPUB files", "*.epub")]
)
if file_path:
book = self.service.load_book(file_path)
print(f"Loaded: {book.title} by {book.author}")
# In a real app, we'd pass this to another feature
Slice 2: Chapter Navigation Feature
features/chapter_navigation/models.py
from dataclasses import dataclass
@dataclass
class Chapter:
title: str
content: str
position: int
features/chapter_navigation/services.py
from typing import List
from .models import Chapter
class ChapterNavigationService:
def __init__(self, chapters: List[Chapter]):
self.chapters = chapters
self.current_position = 0
def get_current_chapter(self) -> Chapter:
return self.chapters[self.current_position]
def next_chapter(self) -> Chapter:
if self.current_position < len(self.chapters) - 1:
self.current_position += 1
return self.get_current_chapter()
def previous_chapter(self) -> Chapter:
if self.current_position > 0:
self.current_position -= 1
return self.get_current_chapter()
def go_to_chapter(self, position: int) -> Chapter:
if 0 <= position < len(self.chapters):
self.current_position = position
return self.get_current_chapter()
features/chapter_navigation/ui.py
import tkinter as tk
from tkinter import ttk
from .services import ChapterNavigationService
class ChapterNavigationUI:
def __init__(self, root: tk.Tk, service: ChapterNavigationService):
self.root = root
self.service = service
self.setup_ui()
def setup_ui(self):
# Navigation buttons
nav_frame = tk.Frame(self.root)
nav_frame.pack(fill=tk.X, padx=5, pady=5)
self.prev_button = tk.Button(
nav_frame,
text="Previous",
command=self.show_previous
)
self.prev_button.pack(side=tk.LEFT)
self.next_button = tk.Button(
nav_frame,
text="Next",
command=self.show_next
)
self.next_button.pack(side=tk.RIGHT)
# Chapter content display
self.content_text = tk.Text(self.root, wrap=tk.WORD)
self.content_text.pack(expand=True, fill=tk.BOTH, padx=5, pady=5)
# Chapter selector
self.chapter_combobox = ttk.Combobox(
self.root,
state="readonly"
)
self.chapter_combobox.pack(fill=tk.X, padx=5, pady=5)
self.chapter_combobox.bind("<<ComboboxSelected>>", self.on_chapter_selected)
# Initialize with first chapter
self.update_display()
def update_display(self):
current_chapter = self.service.get_current_chapter()
self.content_text.delete(1.0, tk.END)
self.content_text.insert(tk.END, current_chapter.content)
# Update chapter list if not already populated
if not self.chapter_combobox['values']:
chapters = [chap.title for chap in self.service.chapters]
self.chapter_combobox['values'] = chapters
self.chapter_combobox.current(self.service.current_position)
def show_previous(self):
self.service.previous_chapter()
self.update_display()
def show_next(self):
self.service.next_chapter()
self.update_display()
def on_chapter_selected(self, event):
selection = self.chapter_combobox.current()
self.service.go_to_chapter(selection)
self.update_display()
Shared EPUB Parser
shared/epub_parser.py
import zipfile
import xml.etree.ElementTree as ET
from typing import Dict, List, Optional
class EPUBParser:
def parse_epub(self, file_path: str) -> Dict:
"""Parse an EPUB file and extract metadata and content"""
with zipfile.ZipFile(file_path) as epub:
# Parse container.xml to find the root file
with epub.open('META-INF/container.xml') as container_file:
container = ET.parse(container_file)
rootfile_path = container.find('.//{*}rootfile').attrib['full-path']
# Parse the root file (usually content.opf)
with epub.open(rootfile_path) as rootfile:
root = ET.parse(rootfile)
namespace = {'opf': 'http://www.idpf.org/2007/opf'}
# Extract metadata
title = root.find('.//opf:metadata/opf:title', namespace).text
author = root.find('.//opf:metadata/opf:creator', namespace).text
# Extract manifest and spine to get chapter order
manifest = {item.attrib['id']: item.attrib['href']
for item in root.findall('.//opf:manifest/opf:item', namespace)}
spine = [item.attrib['idref'] for item in root.findall('.//opf:spine/opf:itemref', namespace)]
# Extract chapters
chapters = []
for item_id in spine:
chapter_path = manifest[item_id]
with epub.open(chapter_path) as chapter_file:
chapter_content = chapter_file.read().decode('utf-8')
# Simple extraction - in real app would need proper HTML parsing
chapters.append({
'title': self._extract_title(chapter_content),
'content': chapter_content
})
return {
'title': title,
'author': author,
'chapters': chapters
}
def _extract_title(self, html_content: str) -> str:
"""Simple title extraction from HTML content"""
# In a real app, use BeautifulSoup or similar
if '<title>' in html_content:
start = html_content.find('<title>') + len('<title>')
end = html_content.find('</title>')
return html_content[start:end].strip()
return "Untitled Chapter"
3. Main Application
main.py
import tkinter as tk
from shared.epub_parser import EPUBParser
from features.book_loading.services import BookLoadingService
from features.book_loading.ui import BookLoadingUI
from features.chapter_navigation.services import ChapterNavigationService
from features.chapter_navigation.ui import ChapterNavigationUI
class EPUBReaderApp:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("EPUB Reader")
self.root.geometry("800x600")
# Shared services
self.epub_parser = EPUBParser()
# Initialize features
self.book_loading_service = BookLoadingService(self.epub_parser)
self.book_loading_ui = BookLoadingUI(self.root, self.book_loading_service)
# Chapter navigation will be initialized after book is loaded
self.chapter_navigation_service = None
self.chapter_navigation_ui = None
# Connect book loading to chapter navigation
self.book_loading_service.load_book_callback = self.on_book_loaded
def on_book_loaded(self, book_metadata):
"""Callback when a book is successfully loaded"""
# Convert book metadata to chapters for navigation
chapters = [
Chapter(
title=chapter['title'],
content=chapter['content'],
position=idx
)
for idx, chapter in enumerate(book_metadata.chapters)
]
# Initialize chapter navigation
self.chapter_navigation_service = ChapterNavigationService(chapters)
self.chapter_navigation_ui = ChapterNavigationUI(
self.root,
self.chapter_navigation_service
)
# Hide the open button after loading
self.book_loading_ui.open_button.pack_forget()
if __name__ == "__main__":
root = tk.Tk()
app = EPUBReaderApp(root)
root.mainloop()
Benefits of This Approach
-
Incremental Development: You can build and test the book loading feature completely before moving to chapter navigation.
-
Isolation of Features: Each feature is self-contained, making it easier to modify or replace individual components.
-
Clear Dependencies: Features can depend on shared services but are otherwise independent.
-
Easier Testing: Each vertical slice can be tested in isolation with its own unit and integration tests.
-
Flexible UI: The UI components can be easily swapped (e.g., from Tkinter to PyQt) without affecting other features.
Next Steps for Expansion
To build a complete EPUB reader, you would add more vertical slices for features like:
- Bookmarking: Allow users to save and return to specific locations
- Search: Implement full-text search within the book
- Annotations: Enable highlighting and note-taking
- Settings: Customize font size, colors, etc.
- Library Management: Organize and manage multiple books
Each of these would be implemented as separate vertical slices with their own UI, services, and models, while potentially sharing some common infrastructure.