פרויקט אמצעMidterm project
מחברים הכול לגרסה 1.0, עם תכנון, בדיקות והצגה.
Put it all together into version 1.0, with planning, tests and a demo.
המודלThe model
תזכורת: מה ביקשוReminder: the task
כתבו 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().
הפתרון המלא והפלט שלוFull solution and its output
from dataclasses import dataclass, field, asdict
@dataclass
class Book:
title: str
author: str
pages: int
read: int = 0
tags: list[str] = field(default_factory=list)
def progress(self) -> int:
return round(self.read / self.pages * 100) if self.pages else 0
def read_pages(self, n: int) -> None:
self.read = max(0, min(self.pages, self.read + n))
def to_dict(self) -> dict:
return asdict(self)
b = Book("Dune", "Frank Herbert", 412)
b.read_pages(500)
print(b.progress(), b.to_dict())100 {'title': 'Dune', 'author': 'Frank Herbert', 'pages': 412, 'read': 412, 'tags': []}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
האחסוןThe storage
תזכורת: מה ביקשוReminder: the task
כתבו 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).
הפתרון המלא והפלט שלוFull solution and its output
import json
from dataclasses import dataclass, field, asdict
from pathlib import Path
@dataclass
class Book:
title: str
author: str
pages: int
read: int = 0
tags: list = field(default_factory=list)
def load(path):
path = Path(path)
if not path.exists():
return []
try:
return [Book(**d) for d in json.loads(path.read_text(encoding="utf-8"))]
except json.JSONDecodeError:
print("warning: broken file")
return []
def save(path, books):
path = Path(path)
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps([asdict(b) for b in books], ensure_ascii=False), encoding="utf-8")
tmp.replace(path)
save("s.json", [Book("Dune", "Frank Herbert", 412, tags=["sci-fi"])])
print(load("s.json"))
Path("bad.json").write_text("[{")
print(load("bad.json"), load("none.json"))[Book(title='Dune', author='Frank Herbert', pages=412, read=0, tags=['sci-fi'])] warning: broken file [] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הממשקThe interface
תזכורת: מה ביקשוReminder: the task
כתבו 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%)").
הפתרון המלא והפלט שלוFull solution and its output
import argparse
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int
read: int = 0
def run(argv, books):
p = argparse.ArgumentParser(prog="shelf")
sub = p.add_subparsers(dest="cmd", required=True)
a = sub.add_parser("add")
a.add_argument("title"); a.add_argument("author"); a.add_argument("pages", type=int)
r = sub.add_parser("read")
r.add_argument("title"); r.add_argument("pages", type=int)
sub.add_parser("stats")
args = p.parse_args(argv)
if args.cmd == "add":
books.append(Book(args.title, args.author, args.pages))
return 0, f"added {args.title}"
if args.cmd == "read":
book = next((b for b in books if b.title.lower() == args.title.lower()), None)
if book is None:
return 1, f"not found: {args.title}"
book.read = min(book.pages, book.read + args.pages)
return 0, f"{book.title}: {round(book.read / book.pages * 100)}%"
total = sum(b.pages for b in books)
done = sum(b.read for b in books)
return 0, f"{len(books)} books, {done}/{total} pages ({round(done / total * 100) if total else 0}%)"
shelf = []
for argv in (["add", "Dune", "Frank Herbert", "400"], ["read", "dune", "100"], ["read", "Emma", "5"], ["stats"]):
print(run(argv, shelf))(0, 'added Dune') (0, 'Dune: 25%') (1, 'not found: Emma') (0, '1 books, 100/400 pages (25%)')
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
בדיקות לפרויקטTests for the project
תזכורת: מה ביקשוReminder: the task
נתונה הפונקציה 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.
הפתרון המלא והפלט שלוFull solution and its output
def run(argv, books):
cmd = argv[0]
if cmd == "add":
books.append({"title": argv[1], "pages": int(argv[3]), "read": 0})
return 0, f"added {argv[1]}"
if cmd == "read":
b = next((b for b in books if b["title"].lower() == argv[1].lower()), None)
if b is None:
return 1, f"not found: {argv[1]}"
b["read"] = min(b["pages"], b["read"] + int(argv[2]))
return 0, f"{b['title']}: {round(b['read'] / b['pages'] * 100)}%"
total = sum(b["pages"] for b in books)
done = sum(b["read"] for b in books)
return 0, f"{len(books)} books, {done}/{total} pages ({round(done / total * 100) if total else 0}%)"
def test_add():
books = []
assert run(["add", "Dune", "F", "400"], books) == (0, "added Dune") and len(books) == 1
def test_read():
books = []
run(["add", "Dune", "F", "400"], books)
assert run(["read", "dune", "100"], books) == (0, "Dune: 25%")
def test_read_past_end():
books = []
run(["add", "Dune", "F", "400"], books)
assert run(["read", "Dune", "999"], books) == (0, "Dune: 100%") and books[0]["read"] == 400
def test_missing_book():
assert run(["read", "Emma", "5"], []) == (1, "not found: Emma")
def test_empty_stats():
assert run(["stats"], []) == (0, "0 books, 0/0 pages (0%)")
tests = [f for n, f in list(globals().items()) if n.startswith("test_")]
for t in tests:
t()
print(len(tests), "tests passed")5 tests passed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף 1.0: הגשהShelf 1.0: submission
תזכורת: מה ביקשוReminder: the task
על המחשב שלכם: הרכיבו את הפרויקט מהתרגילים בתיקייה אחת (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.
הפתרון המלא והפלט שלוFull solution and its output
python3 -m pytest -q
python3 cli.py add Dune "Frank Herbert" 412
python3 cli.py read dune 103
python3 cli.py stats
git add .
git commit -m "Shelf 1.0"
git pushיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
החלפת אחסוןSwapping the storage
תזכורת: מה ביקשוReminder: the task
הוכיחו את הפרדת האחריות: כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
import json
import sqlite3
from pathlib import Path
class JsonStorage:
def __init__(self, path):
self.path = Path(path)
def load(self):
return json.loads(self.path.read_text()) if self.path.exists() else []
def save(self, books):
self.path.write_text(json.dumps(books))
class SqliteStorage:
def __init__(self, path):
self.con = sqlite3.connect(path)
self.con.row_factory = sqlite3.Row
with self.con:
self.con.execute("CREATE TABLE IF NOT EXISTS books (title TEXT, pages INTEGER, read INTEGER)")
def load(self):
return [dict(r) for r in self.con.execute("SELECT title, pages, read FROM books ORDER BY rowid")]
def save(self, books):
with self.con:
self.con.execute("DELETE FROM books")
self.con.executemany("INSERT INTO books VALUES (:title, :pages, :read)", books)
def stats(storage):
books = storage.load()
return f"{len(books)} books, {sum(b['read'] for b in books)}/{sum(b['pages'] for b in books)} pages"
data = [{"title": "Dune", "pages": 412, "read": 103}, {"title": "Emma", "pages": 474, "read": 0}]
for store in (JsonStorage("shelf.json"), SqliteStorage(":memory:")):
store.save(data)
print(type(store).__name__, "->", stats(store))JsonStorage -> 2 books, 103/886 pages SqliteStorage -> 2 books, 103/886 pages
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ייבוא מקובץ CSVImporting from CSV
תזכורת: מה ביקשוReminder: the task
הוסיפו למדף פקודת ייבוא: 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}.
הפתרון המלא והפלט שלוFull solution and its output
import csv
import io
def import_csv(text, books):
index = {b["title"].lower(): b for b in books}
result = {"added": 0, "updated": 0, "skipped": 0}
for row in csv.DictReader(io.StringIO(text)):
title = (row.get("title") or "").strip()
try:
pages = int(row["pages"])
read = int(row.get("read") or 0)
except (ValueError, TypeError):
title = ""
if not title:
result["skipped"] += 1
continue
if title.lower() in index:
book = index[title.lower()]
if read > book["read"]:
book["read"] = min(read, book["pages"])
result["updated"] += 1
else:
book = {"title": title, "author": row.get("author", "").strip(), "pages": pages, "read": min(read, pages)}
books.append(book)
index[title.lower()] = book
result["added"] += 1
return result
shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412, "read": 50}]
text = "title,author,pages,read\ndune,Frank Herbert,412,120\nEmma,Jane Austen,474,\n,Nobody,10,1\nMatilda,Roald Dahl,lots,0\n"
print(import_csv(text, shelf))
print([(b["title"], b["read"]) for b in shelf]){'added': 1, 'updated': 1, 'skipped': 2}
[('Dune', 120), ('Emma', 0)]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.