Skip to content
Discussion options

You must be logged in to vote

Here's a complete, correct fetch_post for that scaffold:

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 None

Three details that make this the "exam answer" version:

  • import urllib.error is not optional. import urllib.request does not guarantee the urllib.error name is bound — the subtlety has bitten everyone once. HTTPError (404s etc.) subclasses URLError, so the one tuple catches connection failures and HTTP errors.
  • json.loa…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by dab00gieman
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants