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

PythonPython
31
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

פרויקט אמצעMidterm project

מחברים הכול לגרסה 1.0, עם תכנון, בדיקות והצגה.

Put it all together into version 1.0, with planning, tests and a demo.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. למה לפצל ל-models / storage / cli?Why split into models / storage / cli?

2. מה עושה tmp_path בבדיקה?What does tmp_path do in a test?

3. מה זה MVP?What is an MVP?

תרגיליםExercises

תרגילExercise 1

המודלThe model

כתבו dataclass Book עם title, author, pages, read=0, tags (רשימה ריקה), ומתודות progress() (אחוז מעוגל, 0 אם pages הוא 0), read_pages(n) (לא עוברים את pages, ולא יורדים מתחת ל-0) ו-to_dict().

Write a Book dataclass with title, author, pages, read=0, tags (an empty list), and methods progress() (rounded percent, 0 if pages is 0), read_pages(n) (never past pages, never below 0) and to_dict().

איך הפלט אמור להיראות?What should the output look like?
100 {'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412, 'read': 412, 'tags': []}
main.py
רמזHint 1: self.read = max(0, min(self.pages, self.read + n))self.read = max(0, min(self.pages, self.read + n))
רמזHint 2: asdict(self)asdict(self)
לפתרוןSolution
תרגילExercise 2

האחסוןThe storage

כתבו load(path) ו-save(path, books) לרשימת Book (המודל נתון): save כותבת דרך קובץ זמני, load מחזירה [] לקובץ חסר, וגם לקובץ פגום (ומדפיסה warning: broken file).

Write load(path) and save(path, books) for a list of Book (the model is given): save writes via a temp file, load returns [] for a missing file, and also for a broken one (printing warning: broken file).

איך הפלט אמור להיראות?What should the output look like?
[Book(title='Dune', author='Frank Herbert', pages=412, read=0, tags=['sci-fi'])]
warning: broken file
[] []
main.py
רמזHint 1: [Book(**d) for d in json.loads(...)][Book(**d) for d in json.loads(...)]
רמזHint 2: except json.JSONDecodeError:except json.JSONDecodeError:
לפתרוןSolution
תרגילExercise 3

הממשקThe interface

כתבו run(argv, books) (books היא רשימת Book שמתעדכנת במקום) עם add TITLE AUTHOR PAGES, read TITLE PAGES, stats. מחזירה (code, text): add → (0, "added TITLE"); read → (0, "TITLE: P%") או (1, "not found: TITLE"); stats → (0, "N books, R/T pages (P%)").

Write run(argv, books) (books is a list of Book updated in place) with add TITLE AUTHOR PAGES, read TITLE PAGES, stats. Returns (code, text): add → (0, "added TITLE"); read → (0, "TITLE: P%") or (1, "not found: TITLE"); stats → (0, "N books, R/T pages (P%)").

איך הפלט אמור להיראות?What should the output look like?
(0, 'added Dune')
(0, 'Dune: 25%')
(1, 'not found: Emma')
(0, '1 books, 100/400 pages (25%)')
main.py
רמזHint 1: next((b for b in books if ...), None) מוצא ספר.next((b for b in books if ...), None) finds a book.
רמזHint 2: אחוז כולל: 0 אם אין עמודים בכלל.Overall percent: 0 if there are no pages at all.
לפתרוןSolution
תרגילExercise 4

בדיקות לפרויקטTests for the project

נתונה הפונקציה run מהתרגיל הקודם (בגרסה מקוצרת). כתבו לפחות חמש פונקציות test_... שמכסות: הוספה, קריאה, קריאה מעבר לסוף הספר, ספר שלא קיים (קוד 1), ו-stats של מדף ריק. הלולאה בסוף מריצה אותן.

Given the run function from the previous exercise (in a short version). Write at least five test_... functions covering: adding, reading, reading past the end of the book, a missing book (code 1), and stats on an empty shelf. The loop at the end runs them.

איך הפלט אמור להיראות?What should the output look like?
5 tests passed
main.py
רמזHint 1: כל בדיקה יוצרת books = [] משלה.Each test makes its own books = [].
רמזHint 2: code, text = run([...], books) ואז assert על שניהם.code, text = run([...], books) then assert on both.
לפתרוןSolution
תרגילExercise 5

מדף 1.0: הגשהShelf 1.0: submission

פרויקט מלווהCompanion project נבדק ידניתSelf-checked

על המחשב שלכם: הרכיבו את הפרויקט מהתרגילים בתיקייה אחת (models.py, storage.py, cli.py, test_shelf.py, README.md, .gitignore), הריצו python3 -m pytest, וודאו שהכלי עובד מהטרמינל. עברו על המחוון, בצעו לפחות 5 commits לאורך הדרך, והעלו ל-GitHub.

On your computer: assemble the project from the exercises in one folder (models.py, storage.py, cli.py, test_shelf.py, README.md, .gitignore), run python3 -m pytest, and make sure the tool works from the terminal. Go through the rubric, make at least 5 commits along the way, and push to GitHub.

רמזHint 1: commit אחרי כל קובץ שעובד: "Add Book model", "Add JSON storage"...Commit after each working file: "Add Book model", "Add JSON storage"...
רמזHint 2: לפני ההגשה: לשכפל את ה-repo לתיקייה חדשה ולנסות להריץ לפי ה-README בלבד.Before submitting: clone the repo into a new folder and try running it from the README alone.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

החלפת אחסוןSwapping the storage

הוכיחו את הפרדת האחריות: כתבו SqliteStorage(path) עם אותו ממשק כמו האחסון ב-JSON (load() מחזירה רשימת מילונים, save(books) שומרת את כולם במקום מה שהיה), ו-JsonStorage(path) עם אותו ממשק. הפונקציה stats(storage) עובדת עם שניהם בלי לדעת מי זה.

Prove separation of concerns: write SqliteStorage(path) with the same interface as the JSON storage (load() returns a list of dicts, save(books) stores them all, replacing what was there), and JsonStorage(path) with the same interface. The function stats(storage) works with both without knowing which it is.

איך הפלט אמור להיראות?What should the output look like?
JsonStorage -> 2 books, 103/886 pages
SqliteStorage -> 2 books, 103/886 pages
main.py
רמזHint 1: ב-save של SQLite: DELETE FROM books ואז executemany, בתוך with con:.In SQLite's save: DELETE FROM books then executemany, inside with con:.
רמזHint 2: con.row_factory = sqlite3.Row ו-dict(r).con.row_factory = sqlite3.Row and dict(r).
לפתרוןSolution
אתגרChallenge 2

ייבוא מקובץ CSVImporting from CSV

הוסיפו למדף פקודת ייבוא: import_csv(text, books) שמקבלת CSV עם title,author,pages,read (read אופציונלי), מוסיפה ספרים חדשים, מעדכנת את read של ספרים קיימים (לפי כותרת בלי רגישות לאותיות, רק אם הערך החדש גדול יותר), מדלגת על שורות פגומות (pages לא מספר או חסר title), ומחזירה מילון {"added": N, "updated": N, "skipped": N}.

Add an import command to the shelf: import_csv(text, books) taking CSV with title,author,pages,read (read optional), adding new books, updating read on existing books (by title, case-insensitive, only if the new value is bigger), skipping broken rows (pages not a number or no title), and returning {"added": N, "updated": N, "skipped": N}.

איך הפלט אמור להיראות?What should the output look like?
{'added': 1, 'updated': 1, 'skipped': 2}
[('Dune', 120), ('Emma', 0)]
main.py
רמזHint 1: try/except ValueError סביב int(row["pages"]).try/except ValueError around int(row["pages"]).
רמזHint 2: מילון עזר: index = {b["title"].lower(): b for b in books}.A helper dict: index = {b["title"].lower(): b for b in books}.
לפתרוןSolution

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