Flet · lesson 3 of 6
Parts in this lesson
ALibraryPresenter(library, storage)the middle layer
BRow(...)3.6: a frozen dataclass of text
CMessage(text, ok)a refusal, as a value
Dexcept LibraryError4.8: one family of errors

A presenter between the app and the library

Last updated

An app is hard to test: something has to click it. The library is easy to test, but it speaks in objects and errors, not in text for a screen. In this lesson you'll put a small class between them, a presenter, which turns the library into rows and messages and never imports Flet. It runs in this page, and pytest can test it.

By the end of this lesson you can

  • Explain the Model–View–Presenter pattern, and what each part may know
  • Use a presenter that turns library objects into rows and refusals into messages
  • Say what goes wrong when a library error reaches a button's handler
  • Test the presenter with pytest, without opening the app

Three parts, three jobs

An app that does everything in its button handlers gets hard to change and harder to test. The usual fix is to split it into three parts, each with one job. This split is called Model–View–Presenter:

PartHere it's…Its jobIt knows about…
Modelthe capstone's Library, unchangedthe rules: lending, fines, savingnothing outside itself
PresenterLibraryPresenter, newturns the model into text for the screen, and the user's actions into model callsthe model, but no toolkit
Viewthe Flet controlsshow what the presenter gives them, and pass on clicksthe presenter, and Flet

Each part only talks to its neighbour. The view never calls Library itself, and the presenter never imports flet. So the same presenter would work behind any toolkit, and a test can use it without opening anything.

It's the same idea as the capstone's menu (lesson C.7), which only read and printed, and left every rule to the library. The presenter does the menu's job for an app.

The presenter

Make a package for the app, library_gui, next to library/ in your project folder, with an empty __init__.py, and put the presenter in it:

The project folder
your project folder
├── library/             the capstone's package
├── library_gui/         new: the app
│   ├── __init__.py      empty
│   └── presenter.py
└── tests/
    ├── conftest.py
    └── test_presenter.py   new

Here's the reference's. Read the two small dataclasses first:

How the reference does it library_gui/presenter.py, lines 15–36
@dataclass(frozen=True)
class Row:
    """One line of the catalogue table, already turned into text."""

    item_id: str
    title: str
    kind: str
    state: str
    due: str


@dataclass(frozen=True)
class Message:
    """What to tell the user after they do something: ok is False for a refusal."""

    text: str
    ok: bool


def money(cents: int) -> str:
    return f"${cents // 100}.{cents % 100:02}"

A Row is one line of the catalogue table, already turned into text: the app just shows the five strings. A Message is what to tell the user after they do something, and ok says whether it worked. Both are frozen (lesson 3.6), because they're answers, not things to change.

Now the class itself:

How the reference does it library_gui/presenter.py, lines 38–86
class LibraryPresenter:
    def __init__(self, library: Library, storage: Storage) -> None:
        self._library = library
        self._storage = storage

    def rows(self, search: str = "") -> list[Row]:
        """The catalogue, or the items that match a search, in title order."""
        rows = []
        for item in self._library.catalogue.search(search):
            loan = self._library.loan_of(item.item_id)
            if not item.can_lend():
                state, due = "Reference", ""
            elif loan:
                who = self._library.member(loan.member_id).get_name()
                state, due = f"Out: {who}", loan.due_on.isoformat()
            else:
                state, due = "In", ""
            rows.append(Row(item.item_id, item.title, item.kind, state, due))
        return rows

    def members(self) -> list[tuple[str, str]]:
        """Every member as (id, name), in name order, for a drop-down."""
        people = sorted(self._library.members(), key=lambda m: m.get_name())
        return [(m.get_id(), m.get_name()) for m in people]

    def lend(self, item_id: str, member_id: str) -> Message:
        if not item_id or not member_id:
            return Message("Choose an item and a member first.", False)
        try:
            loan = self._library.lend(item_id, member_id)
        except LibraryError as e:
            return Message(f"Sorry: {e}.", False)
        self._storage.save(self._library)
        title = self._library.catalogue.get(item_id).title
        name = self._library.member(member_id).get_name()
        return Message(f"Lent {title} to {name}. Due back {loan.due_on}.", True)

    def give_back(self, item_id: str) -> Message:
        if not item_id:
            return Message("Choose an item first.", False)
        try:
            fine = self._library.give_back(item_id)
        except LibraryError as e:
            return Message(f"Sorry: {e}.", False)
        self._storage.save(self._library)
        title = self._library.catalogue.get(item_id).title
        if fine:
            return Message(f"{title} is back. Fine: {money(fine)}.", True)
        return Message(f"{title} is back, on time.", True)
  • rows asks the catalogue to search, then works out each item's state: in, out with whom and until when, or a reference book.
  • lend and give_back call the library inside try. A LibraryError (lesson C.4's family of refusals) becomes a Message with ok=False. Nothing is raised.
  • After every change, the presenter saves. The app never has to remember.

Here it is at work. There's no Flet in it, so it runs in this page. Press Run:

Step 2 code
Edit the code, then run it again

The three lend calls give one success and two refusals, all as plain values. Try a change: take Dune back with presenter.give_back("b1"), and print the rows again.

When a refusal reaches the app

The wrong way. Without a presenter, a button's handler calls the library straight away. Here's what a Lend button might do. Press Run:

Step 3 code raw.py
Edit the code, then run it again

The first loan works. The second raises NotAvailable, because a reference book can't be borrowed, and the program stops.

In a Flet app it's no better. The handler stops part-way, the traceback goes to the terminal (some versions of Flet also show it in the app), and nothing the user can act on appears: no message saying a reference book stays in the library. To them the button just looks broken.

The presenter's except LibraryError is the fix: a refusal becomes a Message, and the app shows it (lesson F.5 puts it in a pop-up). Notice it catches only LibraryError. A real bug, like a typo in a method name, should still show up loudly.

Why does the presenter catch LibraryError and not every Exception?

Test it without the app

The presenter is plain Python, so it's tested like the rest of the capstone. Save the tests as tests/test_presenter.py. They use the library and clock fixtures from the capstone's conftest.py (lesson C.9), and MemoryStorage, so nothing touches your real library.json:

How the reference does it tests/test_presenter.py, lines 1–48
"""The presenter is plain Python, so it's tested without opening a window."""
from library.storage import MemoryStorage
from library_gui.presenter import LibraryPresenter, Row


def make(library):
    storage = MemoryStorage()
    return LibraryPresenter(library, storage), storage


def test_rows_in_title_order(library):
    presenter, _ = make(library)
    titles = [row.title for row in presenter.rows()]
    assert titles == ["Atlas of the World", "Dune", "Emma", "Rivers of Ice"]


def test_rows_show_state(library):
    presenter, _ = make(library)
    presenter.lend("b1", "sam")
    rows = {row.item_id: row for row in presenter.rows()}
    assert rows["b1"] == Row("b1", "Dune", "book", "Out: Sam Okafor", "2026-03-23")
    assert rows["b2"].state == "In"
    assert rows["r1"].state == "Reference"


def test_search(library):
    presenter, _ = make(library)
    assert [row.item_id for row in presenter.rows("austen")] == ["b2"]


def test_members_by_name(library):
    presenter, _ = make(library)
    assert presenter.members() == [("ana", "Ana Lima"), ("sam", "Sam Okafor")]


def test_lend_saves(library):
    presenter, storage = make(library)
    message = presenter.lend("b1", "sam")
    assert message.ok
    assert message.text == "Lent Dune to Sam Okafor. Due back 2026-03-23."
    assert storage.load().loan_of("b1") is not None


def test_refusal_is_a_message(library):
    presenter, storage = make(library)
    message = presenter.lend("r1", "sam")
    assert not message.ok
    assert message.text == "Sorry: Atlas of the World can't be borrowed."
Terminal
pytest tests/test_presenter.py

All eight should pass. Most of what the app does is now tested, and the Flet code that's left is thin: it shows rows and messages, and passes on clicks.

Check

Which part may import flet?
A button's handler raises NotAvailable. What's wrong with that?
What does presenter.lend("r1", "sam") give back for a reference book?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python