Changing Python code to use SSL to call REST

I have Python code to call a REST service that looks something like this:

import urllib 
import urllib2 

username = 'foo' 
password = 'bar' 

passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passwordManager .add_password(None, MY_APP_PATH, username, password) 
authHandler = urllib2.HTTPBasicAuthHandler(passwordManager) 
opener = urllib2.build_opener(authHandler) 
urllib2.install_opener(opener) 

params= { "param1" : param1, 
          "param2" : param2, 
          "param3" : param3 } 

xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read() 
results = MyResponseParser.parse(xmlResults) 

MY_APP_PATH is currently an HTTP URL. I would like to change it to use SSL ("HTTPS"). How can I change this code to use https in the easiest way?

+3
source share
2 answers

Just using HTTPS: // instead of HTTP: // in the URL you are calling should work, at least if you are trying to get to a known / verified server. If necessary, you can use your client-side SSL certificate to secure the transaction API:

mykey = '/path/to/ssl_key_file'
mycert = '/path/to/ssl_cert_file'
opener = urllib2.build_opener(HTTPSClientAuthHandler(mykey, mycert))
opener.add_handler(urllib2.HTTPBasicAuthHandler()) # add HTTP Basic Authentication information...
opener.add_password(user=settings.USER_ID, passwd=settings.PASSWD)
+1
source

, urllib2 httplib, , Python 2.7 HTTPS. , ( -, ): HTTPS.

httplib ( Python 2.7):

. .

( httplib.HTTPSConnection, -: key cer t.)

, :

+3

Source: https://habr.com/ru/post/1764594/


All Articles