LinkedInLearning / learning-python-2896241

This repository is for the Linkedin Learning course: Learning Python
Other
537 stars 994 forks source link

[Version Incompatibility]: urllib.request.urlopen(urlData) cast exceptions on Python 3.11.4 #25

Open tjcchen opened 1 year ago

tjcchen commented 1 year ago

Hello Joe,

I benefit a lot from your Python course on LinkedIn. Thank you so much for such great sharing. Today, I run into one minor problem with the JSONData chapter, namely with this file:

https://github.com/LinkedInLearning/learning-python-2896241/blob/main/Ch5%20-%20Internet%20Data/jsondata_finished.py

The code runs perfectly with Python 3.9.16, but I use Python 3.11.4 for the learning purpose, then I got an error from this method urllib.request.urlopen(urlData), the terminal says:

urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002)>

The error screenshot looks like this:

Screen Shot 2023-06-27 at 4 39 08 PM

I think this should be some kind of version incompatibility issue with Python. And after some investigation, I figure out this can be resolved with a ssl context as follows:

import urllib.request
import ssl

# ...some other code logic ...
urlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_hour.geojson"

context = ssl._create_unverified_context()
webUrl = urllib.request.urlopen(urlData, context=context)

print("result code:", str(webUrl.getcode()))
# ... some other code logic ...

Not sure if this is necessary to clarify in your demo code, I presume there will be more and more software developers using Python 3.11.4 above in the future who are going to take this course since it is so popular and practical, they would run into this problem as well.

Could you please help take a look this. Thank you!

IgorGanapolsky commented 5 months ago

@tjcchen Here is your solution:

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    webUrl = urllib.request.urlopen(urlData, context=ctx)
tjcchen commented 5 months ago

@IgorGanapolsky Thank you! Yeah, I've resolved this issue by similar solution.