נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
36
חלקPart 6: Python בעידן ה-AI וקריירהPython in the AI era & career כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

פרויקט גמר והצגהFinal project & demo

תכנון, בנייה, בדיקות, פרסום והצגה.

Planning, building, testing, publishing and presenting.

01מה זה מדף 2.0What Shelf 2.0 is

פרויקט הגמר מאחד את המדף לגרסה מקצועית: חבילה אחת שיש לה ממשק שורת פקודה (מפגש 27), API (29), מסד נתונים (23), סטטיסטיקה וגרף (24–25), ובדיקות (19). מעליהן אפשר לבחור תוספת אחת או שתיים: המלצות ממודל שפה (33), ייבוא מ-Open Library (22), או גיבוי יומי (28). הנה המבנה, כמפה של שכבות:

The final project turns the shelf into a professional version: one package with a command-line interface (session 27), an API (29), a database (23), stats and a chart (24–25), and tests (19). On top, pick one or two extras: language-model recommendations (33), importing from Open Library (22), or a daily backup (28). Here's the structure, as a map of layers:

layers.py
LAYERS = {
    "models.py": "Book dataclass",
    "storage.py": "SQLite: add, get, list, update",
    "service.py": "rules: progress, stats, search",
    "cli.py": "argparse commands",
    "api.py": "FastAPI routes",
}
USES = {"storage.py": ["models.py"], "service.py": ["storage.py", "models.py"], "cli.py": ["service.py"], "api.py": ["service.py"]}
for name, job in LAYERS.items():
    print(f"shelf/{name:<11} {job:<32} uses {USES.get(name, [])}")
פלטOutput
shelf/models.py   Book dataclass                   uses []
shelf/storage.py  SQLite: add, get, list, update   uses ['models.py']
shelf/service.py  rules: progress, stats, search   uses ['storage.py', 'models.py']
shelf/cli.py      argparse commands                uses ['service.py']
shelf/api.py      FastAPI routes                   uses ['service.py']
אנלוגיה מהחייםReal-life analogy

פרויקט גמר הוא כמו מבחן מעשי בבישול: לא מבשלים כל מנה שלמדתם, אלא ארוחה אחת שלמה ומדויקת שמראה את כל המיומנויות.

A final project is like a practical cooking exam: you don't cook every dish you learned, but one complete, precise meal that shows all the skills.

טעות נפוצהCommon mistake

שכבה עליונה שמדלגת על שכבה ופונה ישר למסד.

A top layer skipping a layer and talking straight to the database.

layers.py
USES = {"cli.py": ["service.py"], "api.py": ["service.py", "storage.py"]}
leaks = [f for f, deps in USES.items() if "storage.py" in deps and f in ("cli.py", "api.py")]
assert not leaks, f"{leaks} talk to storage directly: rules like progress would be duplicated"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/layers.py", line 3, in <module>
    assert not leaks, f"{leaks} talk to storage directly: rules like progress would be duplicated"
           ^^^^^^^^^
AssertionError: ['api.py'] talk to storage directly: rules like progress would be duplicated
בעברית פשוטה: In plain words: AssertionError: ['api.py'] talk to storage directly: ...: אם ה-API עוקף את ה-service, חוקים כמו "לא לעבור את מספר העמודים" ייכתבו פעמיים ויתפצלו. כל ממשק עובר דרך ה-service.AssertionError: ['api.py'] talk to storage directly: ...: if the API bypasses the service, rules like "don't pass the page count" get written twice and drift apart. Every interface goes through the service.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02חבילה ו-pyproject.tomlA package and pyproject.toml

חבילה היא תיקייה עם __init__.py, וכך from shelf.models import Book עובד מכל מקום. הקובץ `pyproject.toml` מתאר את הפרויקט: שם, גרסה, תלויות, ואפילו פקודה בשם shelf שתעבוד בטרמינל אחרי התקנה. pip install -e . מתקין את הפרויקט במצב פיתוח: שינוי בקוד נכנס לתוקף מיד.

A package is a folder with __init__.py, so from shelf.models import Book works from anywhere. The `pyproject.toml` file describes the project: name, version, dependencies, and even a shelf command that works in the terminal after installing. pip install -e . installs the project in development mode: code changes take effect at once.

pyproject.toml
[project]
name = "shelf"
version = "2.0.0"
description = "Track the books you read: CLI, API and stats"
requires-python = ">=3.12"
dependencies = ["fastapi", "uvicorn[standard]"]

[project.optional-dependencies]
dev = ["pytest", "httpx"]

[project.scripts]
shelf = "shelf.cli:main"
read_config.py
import tomllib

text = """[project]
name = \"shelf\"
version = \"2.0.0\"
description = \"Track the books you read: CLI, API and stats\"
requires-python = \">=3.12\"
dependencies = [\"fastapi\", \"uvicorn[standard]\"]

[project.optional-dependencies]
dev = [\"pytest\", \"httpx\"]

[project.scripts]
shelf = \"shelf.cli:main\"
"""
config = tomllib.loads(text)
project = config["project"]
print(project["name"], project["version"], project["requires-python"])
print("needs:", project["dependencies"])
print("command:", project["scripts"])
פלטOutput
shelf 2.0.0 >=3.12
needs: ['fastapi', 'uvicorn[standard]']
command: {'shelf': 'shelf.cli:main'}
אנלוגיה מהחייםReal-life analogy

pyproject.toml הוא כמו תווית על אריזת מוצר: מה בפנים, מה צריך כדי להשתמש בו, ואיך מפעילים.

pyproject.toml is like the label on a product's box: what's inside, what you need to use it, and how to switch it on.

טעות נפוצהCommon mistake

שוכחים את __init__.py ומייבאים עם נקודה מהמקום הלא נכון.

Using a relative import from the wrong place.

cli.py
from .models import Book
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/cli.py", line 1, in <module>
    from .models import Book
ImportError: attempted relative import with no known parent package
בעברית פשוטה: In plain words: ImportError: attempted relative import with no known parent package: ייבוא עם נקודה עובד רק בתוך חבילה. מריצים כ-python -m shelf.cli (או מתקינים עם pip install -e .).ImportError: attempted relative import with no known parent package: a dotted import works only inside a package. Run as python -m shelf.cli (or install with pip install -e .).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

משווים גרסאות כטאפלים, לא כטקסט.

Compare versions as tuples, not as text.

עוד דוגמה: גרסה כמספריםOne more: a version as numbers
example.py
def version(s):
    return tuple(int(x) for x in s.split("."))

print(version("1.10.0") > version("1.9.3"))
print("1.10.0" > "1.9.3")
פלטOutput
True
False
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03שכבת השירותThe service layer

שכבת השירות היא הלב: היא יודעת את החוקים (לא לקרוא יותר מהספר, כותרת לא ריקה, סטטיסטיקה), ומשתמשת באחסון כדי לשמור. גם ה-CLI וגם ה-API רק מתרגמים בקשות לקריאות לשירות. הנה שירות עם אחסון SQLite בזיכרון, ושני "ממשקים" זעירים שמשתמשים בו:

The service layer is the heart: it knows the rules (don't read past the book, no empty title, stats), and uses storage to save. Both the CLI and the API just translate requests into calls to the service. Here's a service with in-memory SQLite storage, and two tiny "interfaces" using it:

service.py
import sqlite3
from dataclasses import dataclass

@dataclass
class Book:
    id: int
    title: str
    pages: int
    read: int = 0

class Storage:
    def __init__(self):
        self.con = sqlite3.connect(":memory:")
        self.con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT UNIQUE, pages INTEGER, read INTEGER DEFAULT 0)")

    def add(self, title, pages):
        with self.con:
            return self.con.execute("INSERT INTO books (title, pages) VALUES (?, ?)", (title, pages)).lastrowid

    def get(self, title):
        row = self.con.execute("SELECT id, title, pages, read FROM books WHERE lower(title) = lower(?)", (title,)).fetchone()
        return Book(*row) if row else None

    def set_read(self, book_id, read):
        with self.con:
            self.con.execute("UPDATE books SET read = ? WHERE id = ?", (read, book_id))

class Service:
    def __init__(self, storage):
        self.storage = storage

    def add(self, title, pages):
        if not title.strip() or pages <= 0:
            raise ValueError("a book needs a title and pages")
        return self.storage.add(title.strip(), pages)

    def read(self, title, pages):
        book = self.storage.get(title)
        if book is None:
            raise LookupError(title)
        new = max(0, min(book.pages, book.read + pages))
        self.storage.set_read(book.id, new)
        return round(new / book.pages * 100)

service = Service(Storage())
cli = lambda argv: f"{argv[1]}: {service.read(argv[1], int(argv[2]))}%" if argv[0] == "read" else f"added #{service.add(argv[1], int(argv[2]))}"
api = lambda method, body: (200, {"progress": service.read(body["title"], body["pages"])})
print(cli(["add", "Dune", "412"]))
print(cli(["read", "dune", "103"]))
print(api("POST", {"title": "Dune", "pages": 500}))
פלטOutput
added #1
dune: 25%
(200, {'progress': 100})
אנלוגיה מהחייםReal-life analogy

שכבת השירות היא כמו המטבח במסעדה עם משלוחים: מי שהזמין באפליקציה ומי שישב בשולחן מקבלים אותה מנה מאותו מטבח.

The service layer is like a restaurant kitchen that also delivers: whoever ordered by app and whoever sat at a table get the same dish from the same kitchen.

טעות נפוצהCommon mistake

חוק שנכתב רק בממשק אחד.

A rule written in only one interface.

service.py
def cli_read(book, pages):
    book["read"] = min(book["pages"], book["read"] + pages)

def api_read(book, pages):
    book["read"] += pages

book = {"pages": 100, "read": 90}
api_read(book, 50)
assert book["read"] <= book["pages"], f"read {book['read']} of {book['pages']}: the API forgot the rule the CLI has"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/service.py", line 9, in <module>
    assert book["read"] <= book["pages"], f"read {book['read']} of {book['pages']}: the API forgot the rule the CLI has"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: read 140 of 100: the API forgot the rule the CLI has
בעברית פשוטה: In plain words: AssertionError: read 140 of 100: the API forgot the rule the CLI has: חוקים גרים בשירות, פעם אחת. שני הממשקים קוראים לו.AssertionError: read 140 of 100: the API forgot the rule the CLI has: rules live in the service, once. Both interfaces call it.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04CI: בדיקות בכל pushCI: tests on every push

CI הוא שומר אוטומטי: בכל push, GitHub Actions מקים מחשב נקי, מתקין את הפרויקט ומריץ את הבדיקות. אם משהו נשבר, רואים סימן אדום ליד ה-commit, עוד לפני שמישהו השתמש בקוד. ההגדרה היא קובץ YAML קצר בתיקייה .github/workflows. כאן אפשר גם לבדוק שהקובץ תקין:

CI is an automatic guard: on every push, GitHub Actions spins up a clean machine, installs the project and runs the tests. If something breaks, you see a red mark next to the commit, before anyone used the code. The setup is a short YAML file in .github/workflows. You can check the file here too:

.github/workflows/tests.yml
name: tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -e ".[dev]"
      - run: python -m pytest -q
check_ci.py
CI = """name: tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -e ".[dev]"
      - run: python -m pytest -q
"""
steps = [line.strip()[2:] for line in CI.splitlines() if line.strip().startswith("- ")]
print(len(steps), "steps")
for s in steps:
    print(" ", s)
assert any("pytest" in s for s in steps), "the workflow never runs the tests"
print("runs on push:", "push" in CI.split("on:")[1].splitlines()[0])
פלטOutput
4 steps
  uses: actions/checkout@v4
  uses: actions/setup-python@v5
  run: pip install -e ".[dev]"
  run: python -m pytest -q
runs on push: True
אנלוגיה מהחייםReal-life analogy

CI הוא כמו גלאי מתכות בכניסה לבניין: כל אחד עובר, כל פעם, בלי יוצא מן הכלל, ולכן אף אחד לא צריך לזכור לבדוק.

CI is like a metal detector at a building's entrance: everyone walks through, every time, no exceptions, so nobody has to remember to check.

טעות נפוצהCommon mistake

הזחה שגויה ב-YAML.

Wrong indentation in YAML.

check_ci.py
ci = "jobs:\n  test:\n    steps:\n    - run: pytest\n   - run: echo done\n"
indents = {len(l) - len(l.lstrip()) for l in ci.splitlines() if l.strip().startswith("- ")}
assert len(indents) == 1, f"list items at indents {sorted(indents)}: YAML items in one list must line up"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/check_ci.py", line 3, in <module>
    assert len(indents) == 1, f"list items at indents {sorted(indents)}: YAML items in one list must line up"
           ^^^^^^^^^^^^^^^^^
AssertionError: list items at indents [3, 4]: YAML items in one list must line up
בעברית פשוטה: In plain words: AssertionError: list items at indents [3, 4]: ...: ב-YAML הזחה היא מבנה, בדיוק כמו בפייתון. GitHub יציג שגיאת תחביר והבדיקות לא ירוצו.AssertionError: list items at indents [3, 4]: ...: in YAML indentation is structure, just like Python. GitHub will show a syntax error and the tests won't run.

05גרסה, יומן שינויים ופרסוםVersion, changelog and release

כשהפרויקט מוכן, נותנים לו גרסה. מדף 1.0 היה הגרסה הראשונה; הוספת API ומסד היא שינוי גדול, ולכן 2.0.0. יומן השינויים מסביר למשתמשים מה חדש. בקוד אפשר אפילו לחשב את הגרסה הבאה לפי סוג השינוי:

When the project is ready, give it a version. Shelf 1.0 was the first; adding an API and a database is a big change, so 2.0.0. The changelog tells users what's new. In code you can even compute the next version from the kind of change:

release.py
def bump(version, change):
    major, minor, patch = map(int, version.split("."))
    if change == "breaking":
        return f"{major + 1}.0.0"
    if change == "feature":
        return f"{major}.{minor + 1}.0"
    return f"{major}.{minor}.{patch + 1}"

v = "1.0.0"
for change, note in [("breaking", "Storage moved to SQLite; JSON files are imported once"), ("feature", "Monthly reading chart"), ("fix", "Progress can no longer pass 100%")]:
    v = bump(v, change)
    print(f"## {v}\n- {note}")
פלטOutput
## 2.0.0
- Storage moved to SQLite; JSON files are imported once
## 2.1.0
- Monthly reading chart
## 2.1.1
- Progress can no longer pass 100%
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

גרסה סמנטית היא כמו מספר מהדורה של ספר: מהדורה חדשה לגמרי, פרק חדש, או תיקון שגיאות דפוס. הקורא יודע מה לצפות.

Semantic versioning is like a book's edition number: an all-new edition, a new chapter, or typo fixes. Readers know what to expect.

טעות נפוצהCommon mistake

מספר גרסה שנבנה כמחרוזת ומשווים אותו כמחרוזת.

A version compared as a string.

release.py
versions = ["2.0.0", "10.0.0", "9.1.0"]
assert max(versions) == "10.0.0", f"max says {max(versions)}: strings compare letter by letter"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/release.py", line 2, in <module>
    assert max(versions) == "10.0.0", f"max says {max(versions)}: strings compare letter by letter"
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: max says 9.1.0: strings compare letter by letter
בעברית פשוטה: In plain words: AssertionError: max says 9.1.0: strings compare letter by letter: ממירים לטאפל מספרים: max(versions, key=lambda v: tuple(map(int, v.split(".")))).AssertionError: max says 9.1.0: strings compare letter by letter: convert to a tuple of numbers: max(versions, key=lambda v: tuple(map(int, v.split(".")))).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06יום ההצגה ומה הלאהDemo day and what's next

ביום ההצגה מציגים את מדף 2.0 בשלוש דקות: הבעיה, הדגמה חיה, ואתגר אחד. מכינים תוכנית ב' (צילומי מסך) כי הדגמות חיות אוהבות להישבר. ומה אחרי? החלק השביעי של הקורס בונה משחקים עם Pygame, ואפשר להתחיל לתרום לפרויקטים פתוחים ב-GitHub. רשימת בדיקה אחרונה:

On demo day, present Shelf 2.0 in three minutes: the problem, a live demo, and one challenge. Prepare a plan B (screenshots) because live demos love to break. And then? The course's seventh part builds games with Pygame, and you can start contributing to open-source projects on GitHub. A final checklist:

demo_day.py
checklist = {
    "pytest passes locally": True,
    "CI is green on GitHub": True,
    "README: install, usage, screenshots": True,
    "demo data loaded (5+ books)": True,
    "plan B screenshots ready": False,
    "3-minute pitch rehearsed twice": True,
}
done = sum(checklist.values())
print(f"{done}/{len(checklist)} ready")
for item, ok in checklist.items():
    if not ok:
        print("todo:", item)
פלטOutput
5/6 ready
todo: plan B screenshots ready
אנלוגיה מהחייםReal-life analogy

יום ההצגה הוא כמו הופעת סיום בחוג מוזיקה: אף אחד לא מצפה לשלמות, אלא לראות כמה התקדמתם ושאתם נהנים לנגן.

Demo day is like a music class's end-of-year concert: nobody expects perfection, just to see how far you've come and that you enjoy playing.

טעות נפוצהCommon mistake

מסתמכים על אינטרנט בהדגמה.

Relying on the internet for the demo.

demo_day.py
def demo(online):
    if not online:
        raise ConnectionError("conference Wi-Fi is down")
    return "recommendation shown"

print(demo(online=False))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/demo_day.py", line 6, in <module>
    print(demo(online=False))
          ~~~~^^^^^^^^^^^^^^
  File "/Users/you/python-course/demo_day.py", line 3, in demo
    raise ConnectionError("conference Wi-Fi is down")
ConnectionError: conference Wi-Fi is down
בעברית פשוטה: In plain words: ConnectionError: conference Wi-Fi is down: הדגמה שתלויה ברשת עלולה ליפול בדיוק ברגע הלא נכון. מכינים נתונים מקומיים ותשובות מוקלטות, כמו שעשינו באתר הזה.ConnectionError: conference Wi-Fi is down: a demo that needs the network may fail at exactly the wrong moment. Prepare local data and recorded replies, just like this site does.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich