כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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
תרגיליםExercises
תרגילExercise 1
מודל pydanticA pydantic model
כתבו מודל Review עם book: str (לפחות תו אחד), stars: int בין 1 ל-5 (Field(ge=1, le=5)), ו-text: str = "". צרו ביקורת תקינה והדפיסו את model_dump().
Write a Review model with book: str (at least one character), stars: int from 1 to 5 (Field(ge=1, le=5)), and text: str = "". Create a valid review and print model_dump().
איך הפלט אמור להיראות?What should the output look like?
{'book': 'Dune', 'stars': 5, 'text': ''}
main.py
רמזHint 1:from pydantic import BaseModel, Fieldfrom pydantic import BaseModel, Field
רמזHint 2:stars: int = Field(ge=1, le=5)stars: int = Field(ge=1, le=5)
כתבו את הלוגיקה של נתיב חיפוש כפונקציה רגילה search(books, q=None, min_pages=0) שמחזירה ספרים שהכותרת או הסופר שלהם מכילים q (בלי רגישות לאותיות; q ריק = כולם) ושיש להם לפחות min_pages עמודים, ממוינים לפי כותרת. כך קל לבדוק אותה, ובשרת מחברים אותה לנתיב.
Write the logic of a search route as a plain function search(books, q=None, min_pages=0) returning books whose title or author contains q (case-insensitive; empty q = all) with at least min_pages pages, sorted by title. That makes it easy to test, and the server just connects it to a route.
איך הפלט אמור להיראות?What should the output look like?
['Matilda', 'The BFG']
['Dune', 'Matilda']
main.py
רמזHint 1:if q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continueif q and q.lower() not in (b["title"] + " " + b["author"]).lower(): continue
בלי FastAPI: כתבו handle(method, path, store) שמדמה שרת קטן לרשימת מטלות ומחזירה (status, body). GET /todos → 200 ורשימה. POST /todos/<text> → 201 ומילון {id, text} חדש. DELETE /todos/<id> → 204 ו-None, או 404 ו-{"detail": "not found"}. כל השאר → 405 ו-{"detail": "not allowed"}.
Without FastAPI: write handle(method, path, store) simulating a tiny to-do server, returning (status, body). GET /todos → 200 and the list. POST /todos/<text> → 201 and a new dict {id, text}. DELETE /todos/<id> → 204 and None, or 404 and {"detail": "not found"}. Anything else → 405 and {"detail": "not allowed"}.
איך הפלט אמור להיראות?What should the output look like?
כתבו מודל BookPatch שבו כל השדות אופציונליים (title: str | None = None, pages: int | None = Field(default=None, gt=0)), ו-apply_patch(book, patch) שמחזירה מילון חדש עם השדות שנשלחו בלבד מעודכנים (patch.model_dump(exclude_unset=True)).
Write a BookPatch model where every field is optional (title: str | None = None, pages: int | None = Field(default=None, gt=0)), and apply_patch(book, patch) returning a new dict with only the sent fields updated (patch.model_dump(exclude_unset=True)).
איך הפלט אמור להיראות?What should the output look like?
כתבו מחלקת שירות ShelfService שתשב מאחורי ה-API (בלי FastAPI, כדי שתרוץ גם כאן): add(data) מקבלת dict, בודקת אותו עם המודל BookIn (title לא ריק, author, pages > 0) ומחזירה ספר עם id; get(id) זורקת KeyError אם אין; list(author=None); delete(id) מחזירה True/False. בשרת האמיתי כל נתיב פשוט קורא למתודה המתאימה.
Write a ShelfService class to sit behind the API (without FastAPI, so it runs here too): add(data) takes a dict, validates it with the BookIn model (non-empty title, author, pages > 0) and returns a book with an id; get(id) raises KeyError if missing; list(author=None); delete(id) returns True/False. In the real server each route just calls the matching method.
איך הפלט אמור להיראות?What should the output look like?
['Matilda'] True False
service.py
רמזHint 1:book = BookIn(**data) זורקת ValidationError על קלט שגוי.book = BookIn(**data) raises ValidationError on bad input.
כתבו מחלקה Router עם דקורטור route(method, pattern) ומתודה dispatch(method, path). pattern יכול לכלול {name} (למשל /books/{id}), ו-dispatch מוצאת את הנתיב המתאים, שולפת את הפרמטרים ומעבירה אותם בשם לפונקציה. מחזירה (200, result), או (404, None) אם אין נתיב.
Write a Router class with a route(method, pattern) decorator and a dispatch(method, path) method. pattern may include {name} (e.g. /books/{id}), and dispatch finds the matching route, extracts the parameters and passes them by name to the function. Returns (200, result), or (404, None) if no route matches.
איך הפלט אמור להיראות?What should the output look like?
(200, {'id': 7}) (200, 'dahl #2') (404, None)
main.py
רמזHint 1:השוו קטע אחרי קטע: p.startswith("{") הוא פרמטר.Compare segment by segment: p.startswith("{") is a parameter.
כתבו RateLimiter(limit, window) עם allow(client, now) שמחזירה True אם ללקוח נשארו בקשות בחלון הזמן האחרון של window שניות (חלון נע), אחרת False (בשרת: 429). בקשות שנדחו לא נספרות.
Write RateLimiter(limit, window) with allow(client, now) returning True if the client still has requests within the last window seconds (a sliding window), else False (in a server: 429). Rejected requests aren't counted.
איך הפלט אמור להיראות?What should the output look like?