APIs עם requestsAPIs with requests
HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.
HTTP, GET, status codes, JSON from the web and handling network errors.
לקרוא תשובת APIReading an API reply
תזכורת: מה ביקשוReminder: the task
המילון 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.
הפתרון המלא והפלט שלוFull solution and its output
reply = {'title': 'Dune', 'authors': [{'key': '/authors/OL79034A'}], 'number_of_pages': 604, 'publishers': ['Ace'], 'publish_date': '1990'}
print(f'{reply["title"]}, {reply["number_of_pages"]} pages, {reply["publishers"][0]}')Dune, 604 pages, Ace
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
סיווג סטטוסClassifying a status
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def explain(code):
kinds = {2: "ok", 3: "redirect", 4: "client error", 5: "server error"}
return kinds.get(code // 100, "unknown")
for c in [200, 404, 503, 301, 99]:
print(c, explain(c))200 ok 404 client error 503 server error 301 redirect 99 unknown
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לבנות כתובתBuilding a URL
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
from urllib.parse import urlencode
def search_url(query, limit=5):
return "https://openlibrary.org/search.json?" + urlencode({"q": query.strip(), "limit": limit})
print(search_url("le petit prince", 2))
print(search_url("Tom & Jerry"))https://openlibrary.org/search.json?q=le+petit+prince&limit=2 https://openlibrary.org/search.json?q=Tom+%26+Jerry&limit=5
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עיבוד תוצאות חיפושProcessing search results
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def summarize(reply):
out = []
for doc in reply.get("docs", []):
if "title" not in doc:
continue
year = doc.get("first_publish_year", "?")
author = (doc.get("author_name") or ["unknown"])[0]
out.append(f'{doc["title"]} ({year}) by {author}')
return out
reply = {"docs": [{"title": "Dune", "author_name": ["Frank Herbert"], "first_publish_year": 1965}, {"title": "Notes"}, {"author_name": ["X"]}]}
for line in summarize(reply):
print(line)Dune (1965) by Frank Herbert Notes (?) by unknown
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 22: מילוי לפי ISBNShelf, step 22: fill in by ISBN
תזכורת: מה ביקשוReminder: the task
כתבו 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().
הפתרון המלא והפלט שלוFull solution and its output
RECORDED = {
"https://openlibrary.org/isbn/9780441172719.json": {'title': 'Dune', 'authors': [{'key': '/authors/OL79034A'}], 'number_of_pages': 604, 'publishers': ['Ace'], 'publish_date': '1990'},
"https://openlibrary.org/authors/OL79034A.json": {"name": "Frank Herbert"},
}
def fake_fetch(url):
return RECORDED.get(url)
def book_from_isbn(isbn, fetch):
data = fetch(f"https://openlibrary.org/isbn/{isbn}.json")
if not data:
return None
author = "unknown"
if data.get("authors"):
person = fetch(f"https://openlibrary.org{data['authors'][0]['key']}.json")
if person:
author = person.get("name", "unknown")
return {"title": data.get("title", ""), "author": author, "pages": data.get("number_of_pages", 0)}
print(book_from_isbn("9780441172719", fake_fetch))
print(book_from_isbn("0000000000", fake_fetch)){'title': 'Dune', 'author': 'Frank Herbert', 'pages': 604}
Noneיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מטמון חכםA smart cache
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def cached(fetch, max_age, clock):
store = {}
def inner(url):
now = clock()
if url in store and now - store[url][0] < max_age:
return store[url][1]
inner.calls += 1
value = fetch(url)
if value is not None:
store[url] = (now, value)
return value
inner.calls = 0
return inner
t = [0]
get = cached(lambda url: {"url": url}, max_age=60, clock=lambda: t[0])
get("a"); get("a"); t[0] = 61; get("a"); get("b")
print(get.calls)3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ניסיון חוזרRetrying
תזכורת: מה ביקשוReminder: the task
כתבו 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.
הפתרון המלא והפלט שלוFull solution and its output
def with_retry(fetch, tries=3, wait=print):
def inner(url):
for attempt in range(tries):
try:
return fetch(url)
except ConnectionError:
if attempt == tries - 1:
raise
wait(2 ** attempt)
return inner
fails = [2]
def flaky(url):
if fails[0] > 0:
fails[0] -= 1
raise ConnectionError("network down")
return "ok: " + url
print(with_retry(flaky, wait=lambda s: print("wait", s))("books"))wait 1 wait 2 ok: books
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.