With urllib2, the latest versions allow to use an optional parameter "context" when calling urlopen.
I put together some code to make use of that:
# For Python 3.0 and later
from urllib.request import urlopen, HTTPError, URLError
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, HTTPError, URLError
import ssl
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
response = urlopen(url=url, context=context)
Running that with my python 2.78 ... I get:
Traceback (most recent call last):
File "test.py", line 5, in <module>
context = ssl.create_default_context()
AttributeError: 'module' object has no attribute 'create_default_context'
So I thought: lets go for python3 then; and now I get:
Traceback (most recent call last):
File "test.py", line 15, in <module>
response = urlopen(url=url, context=context)
TypeError: urlopen() got an unexpected keyword argument 'context'
It took me a while to figure that using that named argument context ... also requires a newer version of python than the 3.4.0 installed on my ubuntu 14.04.
My question: what is the "canonical" way to check if "context" can be used when calling urlopen? Just call it and expect the TypeError? Or do a exact version check on the python I am running in?
I did search here and with google, but maybe I am just missing the right search term ... as I couldnt find anything helpful ...