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

PythonPython
22
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

APIs עם requestsAPIs with requests

HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.

HTTP, GET, status codes, JSON from the web and handling network errors.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-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. מה אומר קוד 404?What does code 404 mean?

2. למה תמיד להוסיף timeout=?Why always add timeout=?

3. איך שולחים ?q=dune&limit=2 נכון?How do you send ?q=dune&limit=2 properly?

תרגיליםExercises

תרגילExercise 1

לקרוא תשובת APIReading an API reply

המילון reply הוא תשובה מוקלטת מ-Open Library. הדפיסו את הכותרת, מספר העמודים ואת ההוצאה הראשונה, בפורמט Dune, 604 pages, Ace.

The dict reply is a recorded Open Library reply. Print the title, the number of pages and the first publisher, as Dune, 604 pages, Ace.

איך הפלט אמור להיראות?What should the output look like?
Dune, 604 pages, Ace
main.py
רמזHint 1: reply["publishers"][0]reply["publishers"][0]
רמזHint 2: f-string עם שלושת הערכים.An f-string with the three values.
לפתרוןSolution
תרגילExercise 2

סיווג סטטוסClassifying a status

כתבו explain(code) שמחזירה "ok" ל-2xx, "redirect" ל-3xx, "client error" ל-4xx, "server error" ל-5xx ו-"unknown" לכל השאר.

Write explain(code) returning "ok" for 2xx, "redirect" for 3xx, "client error" for 4xx, "server error" for 5xx and "unknown" otherwise.

איך הפלט אמור להיראות?What should the output look like?
200 ok
404 client error
503 server error
301 redirect
99 unknown
main.py
רמזHint 1: code // 100 נותן את הספרה הראשונה.code // 100 gives the first digit.
רמזHint 2: מילון: {2: "ok", ...}.get(code // 100, "unknown")A dict: {2: "ok", ...}.get(code // 100, "unknown")
לפתרוןSolution
תרגילExercise 3

לבנות כתובתBuilding a URL

כתבו search_url(query, limit=5) שמחזירה את כתובת החיפוש של Open Library עם הפרמטרים מקודדים נכון, בעזרת urllib.parse.urlencode. לדוגמה search_url("le petit prince", 2) → https://openlibrary.org/search.json?q=le+petit+prince&limit=2.

Write search_url(query, limit=5) returning Open Library's search address with properly encoded parameters, using urllib.parse.urlencode. E.g. search_url("le petit prince", 2) → https://openlibrary.org/search.json?q=le+petit+prince&limit=2.

איך הפלט אמור להיראות?What should the output look like?
https://openlibrary.org/search.json?q=le+petit+prince&limit=2
https://openlibrary.org/search.json?q=Tom+%26+Jerry&limit=5
main.py
רמזHint 1: from urllib.parse import urlencodefrom urllib.parse import urlencode
רמזHint 2: "...search.json?" + urlencode({"q": query, "limit": limit})"...search.json?" + urlencode({"q": query, "limit": limit})
לפתרוןSolution
תרגילExercise 4

עיבוד תוצאות חיפושProcessing search results

כתבו summarize(reply) שמקבלת תשובת חיפוש (מילון עם docs) ומחזירה רשימת מחרוזות "Title (year) by Author". אם חסרה שנה, ?; אם חסר סופר, unknown. דלגו על רשומות בלי title.

Write summarize(reply) that takes a search reply (a dict with docs) and returns strings "Title (year) by Author". A missing year becomes ?; a missing author becomes unknown. Skip records without title.

איך הפלט אמור להיראות?What should the output look like?
Dune (1965) by Frank Herbert
Notes (?) by unknown
main.py
רמזHint 1: doc.get("first_publish_year", "?")doc.get("first_publish_year", "?")
רמזHint 2: (doc.get("author_name") or ["unknown"])[0](doc.get("author_name") or ["unknown"])[0]
לפתרוןSolution
תרגילExercise 5

מדף, צעד 22: מילוי לפי ISBNShelf, step 22: fill in by ISBN

פרויקט מלווהCompanion project

כתבו book_from_isbn(isbn, fetch) ש-fetch(url) שלה מחזירה מילון JSON (או None אם נכשל). היא מביאה את הספר מ-https://openlibrary.org/isbn/<isbn>.json, ואז את שם הסופר מכתובת המחבר (https://openlibrary.org<key>.json), ומחזירה {title, author, pages}, או None אם הספר לא נמצא. בבדיקה מעבירים fetch מזויף שמשתמש במילון מוקלט, ובמחשב שלכם: lambda url: requests.get(url, timeout=10).json().

Write book_from_isbn(isbn, fetch) whose fetch(url) returns a JSON dict (or None on failure). It fetches the book from https://openlibrary.org/isbn/<isbn>.json, then the author's name from the author address (https://openlibrary.org<key>.json), and returns {title, author, pages}, or None if the book isn't found. Tests pass a fake fetch using a recorded dict; on your computer: lambda url: requests.get(url, timeout=10).json().

איך הפלט אמור להיראות?What should the output look like?
{'title': 'Dune', 'author': 'Frank Herbert', 'pages': 604}
None
shelf.py
רמזHint 1: key = data["authors"][0]["key"]key = data["authors"][0]["key"]
רמזHint 2: אם fetch מחזירה None לספר, מחזירים None.If fetch returns None for the book, return None.
לפתרוןSolution

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

אתגרChallenge 1

מטמון חכםA smart cache

כתבו cached(fetch, max_age, clock) שמחזירה פונקציה חדשה: בקריאה ראשונה לכתובת היא קוראת ל-fetch ושומרת את התוצאה עם הזמן clock(). קריאה חוזרת לאותה כתובת תוך פחות מ-max_age שניות מחזירה מהמטמון בלי לקרוא ל-fetch. תוצאה None לא נשמרת. הוסיפו לפונקציה המוחזרת תכונה calls שסופרת קריאות אמיתיות.

Write cached(fetch, max_age, clock) returning a new function: the first call for a URL calls fetch and stores the result with the time clock(). A repeat call for the same URL within max_age seconds returns from the cache without calling fetch. A None result isn't stored. Give the returned function a calls attribute counting real calls.

איך הפלט אמור להיראות?What should the output look like?
3
main.py
רמזHint 1: מילון store[url] = (time, value).A dict store[url] = (time, value).
רמזHint 2: פונקציה פנימית יכולה לקבל תכונה: inner.calls = 0.An inner function can have an attribute: inner.calls = 0.
לפתרוןSolution
אתגרChallenge 2

ניסיון חוזרRetrying

כתבו with_retry(fetch, tries=3, wait=print): מחזירה פונקציה שמנסה fetch(url) עד tries פעמים. אם נזרקת ConnectionError (המובנית של פייתון) מנסים שוב, וקוראים ל-wait(seconds) עם המתנה מכפילה: 1, 2, 4... אם כל הניסיונות נכשלו, זורקים את השגיאה האחרונה.

Write with_retry(fetch, tries=3, wait=print): returns a function trying fetch(url) up to tries times. If a ConnectionError (Python's built-in) is raised, try again, calling wait(seconds) with doubling waits: 1, 2, 4... If every attempt fails, raise the last error.

איך הפלט אמור להיראות?What should the output look like?
wait 1
wait 2
ok: books
main.py
רמזHint 1: לולאה for attempt in range(tries): עם try בפנים.A loop for attempt in range(tries): with try inside.
רמזHint 2: wait(2 ** attempt) רק אם יש עוד ניסיון.wait(2 ** attempt) only if another attempt remains.
לפתרוןSolution

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