נבנה על ידי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.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

בודק שכבותA layer checker

תזכורת: מה ביקשוReminder: the task

כתבו layer_violations(imports, order) שמקבלת מילון קובץ → רשימת קבצים שהוא מייבא, ורשימת שכבות מהנמוכה לגבוהה (["models", "storage", "service", "cli"]). קובץ מותר לייבא רק שכבה נמוכה ממנו. מחזירה רשימה ממוינת של זוגות (from, to) שמפרים את הכלל.

Write layer_violations(imports, order) taking a dict file → list of files it imports, and a list of layers from lowest to highest (["models", "storage", "service", "cli"]). A file may only import a lower layer. Return a sorted list of (from, to) pairs breaking the rule.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def layer_violations(imports, order):
    rank = {name: i for i, name in enumerate(order)}
    return sorted((src, dep) for src, deps in imports.items() for dep in deps if rank[dep] >= rank[src])

imports = {"models": [], "storage": ["models"], "service": ["storage", "cli"], "cli": ["service", "models"]}
print(layer_violations(imports, ["models", "storage", "service", "cli"]))
פלטOutput
[('service', 'cli')]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

קריאת pyprojectReading pyproject

תזכורת: מה ביקשוReminder: the task

כתבו summary(text) שמקבלת תוכן של pyproject.toml ומחזירה מחרוזת name version (python REQ): N deps, commands: a, b, בעזרת tomllib. אם אין scripts, commands: none.

Write summary(text) taking a pyproject.toml's content and returning name version (python REQ): N deps, commands: a, b, using tomllib. With no scripts, commands: none.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import tomllib

def summary(text):
    p = tomllib.loads(text)["project"]
    commands = ", ".join(p.get("scripts", {})) or "none"
    return f'{p["name"]} {p["version"]} (python {p.get("requires-python", "?")}): {len(p.get("dependencies", []))} deps, commands: {commands}'

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\"
"""
print(summary(text))
פלטOutput
shelf 2.0.0 (python >=3.12): 2 deps, commands: shelf

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

גרסה הבאהThe next version

תזכורת: מה ביקשוReminder: the task

כתבו next_version(version, commits) שמקבלת גרסה ורשימת הודעות commit, ומחזירה את הגרסה הבאה: אם הודעה כלשהי מתחילה ב-BREAKING → MAJOR; אחרת אם מתחילה ב-feat → MINOR; אחרת אם יש הודעות → PATCH; בלי הודעות, אותה גרסה.

Write next_version(version, commits) taking a version and commit messages, returning the next version: if any message starts with BREAKING → MAJOR; else if any starts with feat → MINOR; else if there are messages → PATCH; with none, the same version.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
def next_version(version, commits):
    major, minor, patch = map(int, version.split("."))
    if any(c.startswith("BREAKING") for c in commits):
        return f"{major + 1}.0.0"
    if any(c.startswith("feat") for c in commits):
        return f"{major}.{minor + 1}.0"
    if commits:
        return f"{major}.{minor}.{patch + 1}"
    return version

print(next_version("1.4.2", ["fix: typo", "feat: chart"]), next_version("1.4.2", ["BREAKING: new storage"]), next_version("1.4.2", []))
פלטOutput
1.5.0 2.0.0 1.4.2

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

שירות עם חוקיםA service with rules

תזכורת: מה ביקשוReminder: the task

כתבו Service שמקבל אובייקט אחסון (עם add(title, pages) -> id, get(title) -> dict | None, set_read(id, read)) ומממש: add (ValueError לכותרת ריקה או עמודים ≤ 0), read(title, pages) (LookupError לספר חסר, לא עוברים את pages ולא יורדים מתחת ל-0, מחזיר אחוז), ו-stats() (מספר ספרים ואחוז כולל, דרך storage.all()). אחסון בזיכרון נתון.

Write a Service taking a storage object (with add(title, pages) -> id, get(title) -> dict | None, set_read(id, read)) implementing: add (ValueError on an empty title or pages ≤ 0), read(title, pages) (LookupError for a missing book, never past pages or below 0, returns a percent), and stats() (book count and overall percent, via storage.all()). An in-memory storage is given.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
class MemoryStorage:
    def __init__(self):
        self.rows = {}

    def add(self, title, pages):
        new_id = len(self.rows) + 1
        self.rows[new_id] = {"id": new_id, "title": title, "pages": pages, "read": 0}
        return new_id

    def get(self, title):
        return next((r for r in self.rows.values() if r["title"].lower() == title.lower()), None)

    def set_read(self, book_id, read):
        self.rows[book_id]["read"] = read

    def all(self):
        return list(self.rows.values())

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

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

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

    def stats(self):
        books = self.storage.all()
        total = sum(b["pages"] for b in books)
        return len(books), round(sum(b["read"] for b in books) / total * 100) if total else 0

s = Service(MemoryStorage())
s.add("Dune", 400)
s.add("Emma", 100)
print(s.read("dune", 300), s.read("DUNE", 500), s.read("Emma", -10), s.stats())
פלטOutput
75 100 0 (2, 80)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף 2.0: פרויקט הגמרShelf 2.0: the final project

תזכורת: מה ביקשוReminder: the task

על המחשב שלכם: בנו את מדף 2.0 כחבילה shelf/ (models, storage עם SQLite, service, cli, api), pyproject.toml, בדיקות ל-service ול-API (TestClient), README עם צילום מסך של /docs, ו-.github/workflows/tests.yml. הוסיפו תוספת אחת לבחירתכם (גרף, המלצה, ייבוא ISBN או גיבוי). העלו ל-GitHub עם CI ירוק ותגית v2.0.0.

On your computer: build Shelf 2.0 as a shelf/ package (models, SQLite storage, service, cli, api), pyproject.toml, tests for the service and the API (TestClient), a README with a screenshot of /docs, and .github/workflows/tests.yml. Add one extra of your choice (a chart, recommendations, ISBN import or a backup). Push to GitHub with green CI and a v2.0.0 tag.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
Terminal
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
python3 -m pytest -q
shelf add Dune "Frank Herbert" 412
uvicorn shelf.api:app --reload
git tag v2.0.0 && git push --tags

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

מיגרציות מסדDatabase migrations

תזכורת: מה ביקשוReminder: the task

מסדי נתונים משתנים בין גרסאות. כתבו migrate(con, migrations): migrations היא רשימת מחרוזות SQL, והגרסה הנוכחית שמורה ב-PRAGMA user_version. הפונקציה מריצה רק את המיגרציות שעוד לא רצו (לפי אינדקס), כל אחת בטרנזקציה, מעדכנת את user_version ומחזירה את מספר המיגרציות שהורצו.

Databases change between versions. Write migrate(con, migrations): migrations is a list of SQL strings, and the current version is stored in PRAGMA user_version. The function runs only migrations that haven't run yet (by index), each in a transaction, updates user_version and returns how many ran.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import sqlite3

MIGRATIONS = [
    "CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, pages INTEGER)",
    "ALTER TABLE books ADD COLUMN read INTEGER DEFAULT 0",
    "CREATE TABLE reviews (book_id INTEGER, stars INTEGER)",
]

def migrate(con, migrations):
    current = con.execute("PRAGMA user_version").fetchone()[0]
    for i in range(current, len(migrations)):
        with con:
            con.execute(migrations[i])
            con.execute(f"PRAGMA user_version = {i + 1}")
    return len(migrations) - current

con = sqlite3.connect(":memory:")
print(migrate(con, MIGRATIONS[:2]), migrate(con, MIGRATIONS), migrate(con, MIGRATIONS))
print([r[1] for r in con.execute("PRAGMA table_info(books)")], con.execute("PRAGMA user_version").fetchone()[0])
פלטOutput
2 1 0
['id', 'title', 'pages', 'read'] 3

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

בריאות הפרויקטProject health

תזכורת: מה ביקשוReminder: the task

כתבו health(files) שמקבלת מילון נתיב → תוכן של פרויקט, ומחזירה ציון 0–100 ורשימת המלצות: README.md עם ## Install (20), לפחות 5 פונקציות def test_ בקבצי test_*.py (25), .gitignore שמכיל .venv (10), workflow ב-.github/workflows/ שמריץ pytest (20), pyproject.toml עם version (10), ואף קובץ .py לא מכיל מחרוזת שנראית כמו מפתח sk- (15).

Write health(files) taking a dict path → content of a project, returning a 0–100 score and a list of recommendations: README.md with ## Install (20), at least 5 def test_ functions in test_*.py files (25), a .gitignore containing .venv (10), a workflow in .github/workflows/ running pytest (20), pyproject.toml with version (10), and no .py file containing a string that looks like an sk- key (15).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import re

def health(files):
    tests = sum(t.count("def test_") for p, t in files.items() if p.split("/")[-1].startswith("test_"))
    checks = [
        (20, "## Install" in files.get("README.md", ""), "add an Install section to README.md"),
        (25, tests >= 5, f"write more tests ({tests}/5)"),
        (10, ".venv" in files.get(".gitignore", ""), "ignore .venv in .gitignore"),
        (20, any(p.startswith(".github/workflows/") and "pytest" in t for p, t in files.items()), "add a CI workflow that runs pytest"),
        (10, "version" in files.get("pyproject.toml", ""), "set a version in pyproject.toml"),
        (15, not any(p.endswith(".py") and re.search(r"sk-[A-Za-z0-9_-]{12,}", t) for p, t in files.items()), "remove the API key from the code"),
    ]
    return sum(pts for pts, ok, _ in checks if ok), [advice for _, ok, advice in checks if not ok]

project = {
    "README.md": "# Shelf\n## Install\npip install -e .\n",
    "shelf/api.py": 'KEY = "sk-live_0123456789abcdef"\n',
    "tests/test_service.py": "def test_a(): pass\ndef test_b(): pass\ndef test_c(): pass\n",
    ".gitignore": ".venv/\n",
    "pyproject.toml": '[project]\nversion = "2.0.0"\n',
}
score, todo = health(project)
print(score)
for t in todo:
    print("-", t)
פלטOutput
40
- write more tests (3/5)
- add a CI workflow that runs pytest
- remove the API key from the code

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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