Repository navigation
Module 14: urllib error handling for fetch_post — and why not requests?
#18
|
import urllib.request
import json
URL = "https://jsonplaceholder.typicode.com/posts/1"
# TODO: Write a function named 'fetch_post' that makes a GET request to the URL using urllib.
# The function should return the dictionary loaded from the JSON response.
# Handle potential errors and return None if the request fails.For the "handle potential errors" part, which failures should the canonical solution catch — |
Replies: 1 comment
|
Here's a complete, correct import urllib.request
import urllib.error
import json
def fetch_post():
try:
with urllib.request.urlopen(URL) as response:
if response.status != 200:
return None
return json.load(response)
except (urllib.error.URLError, json.JSONDecodeError):
return NoneThree details that make this the "exam answer" version:
Why urllib and not import requests
def fetch_post():
try:
r = requests.get(URL, timeout=10)
r.raise_for_status()
return r.json()
except requests.RequestException:
return None— which is exactly the readability lesson the comparison is meant to land. |
Here's a complete, correct
fetch_postfor that scaffold:Three details that make this the "exam answer" version:
import urllib.erroris not optional.import urllib.requestdoes not guarantee theurllib.errorname is bound — the subtlety has bitten everyone once.HTTPError(404s etc.) subclassesURLError, so the one tuple catches connection failures and HTTP errors.json.loa…