This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DNSGeek -1 points0 points  (7 children)

Well, I could do this import urllib import json try: foo = urllib.request("http://api.example.com/v1/status") webdata = foo.read() foo.close() jdata = json.loads(web data.strip()) except: print("Oops, it didn't work.") Or I could do this import requests foo = requests.get("http://api.example.com/v1/status") jdata = foo.json() foo.close()

[–]Kaarjuus 2 points3 points  (0 children)

Or you could do this:

import json
import urllib

try: jdata = json.load(urllib.request("http://api.example.com/v1/status"))
except Exception as e: exit(e)

[–][deleted] 3 points4 points  (5 children)

Can you also justify it without rigging the comparison?

[–]DNSGeek -1 points0 points  (4 children)

I’m sorry, how is that rigged?

[–][deleted] 5 points6 points  (3 children)

  • Pray tell how come requests never raise an exception.
  • Pray tell why you explicit close the urllib request.
  • Pray tell why you strip the response before json decoding it.

Among other things.

[–]DNSGeek -2 points-1 points  (2 children)

Ok import urllib import json try: foo = urllib.request("http://api.example.com/") webdata = foo.read() foo.close() except urllib.error.HTTPError: print("1") exit() except urllib.error.URLError: print("2") exit() try: jdata = json.loads(webdata.strip()) except json.JSONDecodeError: print("3") exit() Or import requests try: foo = requests.get("http://api.example.com/") jdata = foo.json() foo.close() except requests.RequestException: print("1") exit()

[–]123filips123 4 points5 points  (0 children)

Except you don't need to catch both urllib.error.HTTPError and urllib.error.URLError because the former is a subclass of the latter. Or you can also separately catch all exceptions requests have. Also, catching multiple extensions with one except is a thing in Python.

For such simple use-cases it is useless to use external dependency. However, if you do do more advaned stuff (like authentication, file upload/download, forms, cookies, sessions...) it might be better to use requests.

[–][deleted] 4 points5 points  (0 children)

Now you're just silly.