本文整理匯總了Python中ssl._create_unverified_context方法的典型用法代碼示例。如果您正苦於以下問題:Python ssl._create_unverified_context方法的具體用法?Python ssl._create_unverified_context怎麽用?Python ssl._create_unverified_context使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ssl
的用法示例。
在下文中一共展示了ssl._create_unverified_context方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: retrieve_status_page
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def retrieve_status_page(user, password, url):
try:
ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = ssl._create_unverified_context
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, user, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
req = urllib2.Request(url)
try:
response = urllib2.urlopen(req)
return response.read()
except Exception:
raise CrawlError("can't access to http://%s", url)
示例2: load_mnist
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def load_mnist(training_num=50000):
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')
if not os.path.isfile(data_path):
from six.moves import urllib
origin = (
'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'
)
print('Downloading data from %s to %s' % (origin, data_path))
ctx = ssl._create_unverified_context()
with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f:
f.write(u.read())
print('Done!')
dat = numpy.load(data_path)
X = (dat['X'][:training_num] / 126.0).astype('float32')
Y = dat['Y'][:training_num]
X_test = (dat['X_test'] / 126.0).astype('float32')
Y_test = dat['Y_test']
Y = Y.reshape((Y.shape[0],))
Y_test = Y_test.reshape((Y_test.shape[0],))
return X, Y, X_test, Y_test
示例3: send_sms_builtin
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def send_sms_builtin(self, recipient, sender=None):
"""
Sends SMS through built-in gateway
"""
if not settings.SMS_HTTP_URL:
raise ValueError(_('System is not configured for built-in SMS support.'))
if sender is None:
location = self.created_by.location
sender = location.title
data = urllib.urlencode({
'username' : settings.SMS_HTTP_USERNAME,
'password' : settings.SMS_HTTP_PASSWORD,
'numberto' : recipient.replace(' ', ''),
'numberfrom': sender.encode(SMS_ENCODING),
'message' : self.body.encode(SMS_ENCODING),
})
from ssl import _create_unverified_context
f = urllib.urlopen(settings.SMS_HTTP_URL, data, context=_create_unverified_context())
return f.read()
示例4: send
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def send(self):
pwhash = md5(self.conf['sms_http_password']).hexdigest()
params = {
'username' : self.conf['sms_http_user'],
'password' : pwhash,
'message' : self.body,
'from' : self.sender,
'to' : self.recipient,
}
if self.msg:
dlruri = settings.SERVO_URL + '/api/messages/?id={0}'.format(self.msg.code)
params['notify_url'] = dlruri
params = urllib.urlencode(params)
r = urllib.urlopen(self.URL, params, context=_create_unverified_context()).read()
if 'ERROR:' in r:
raise ValueError(self.ERRORS.get(r, _('Unknown error (%s)') % r))
示例5: postRequest
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def postRequest(self, url, params):
params = urlencode(params)
headers = {"Content-Type" : "application/x-www-form-urlencoded;charset=utf-8"}
req = urllib2.Request(url=url, data=params, headers=headers)
try:
response = urllib2.urlopen(req)
log.debug("%s?%s" % (response.geturl(), params))
return json.loads(response.read())
except urllib2.URLError, e:
log.debug(e)
if hasattr(ssl, '_create_unverified_context'): #for mac os only in order to ignore invalid certificates
try:
context = ssl._create_unverified_context()
response = urllib2.urlopen(req, context=context)
return json.loads(response.read())
except Exception, e:
log.exception(e)
示例6: scan
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def scan(url, redirect, insecure, useragent, postdata, proxy):
request = urllib2.Request(url.geturl())
request.add_header('User-Agent', useragent)
request.add_header('Origin', 'http://hsecscan.com')
request.add_header('Accept', '*/*')
if postdata:
request.add_data(urllib.urlencode(postdata))
build = [urllib2.HTTPHandler()]
if redirect:
build.append(RedirectHandler())
if proxy:
build.append(urllib2.ProxyHandler({'http': proxy, 'https': proxy}))
if insecure:
context = ssl._create_unverified_context()
build.append(urllib2.HTTPSHandler(context=context))
urllib2.install_opener(urllib2.build_opener(*build))
response = urllib2.urlopen(request)
print '>> RESPONSE INFO <<'
print_response(response.geturl(), response.getcode(), response.info())
print '>> RESPONSE HEADERS DETAILS <<'
for header in response.info().items():
check_header(header)
print '>> RESPONSE MISSING HEADERS <<'
missing_headers(response.info().items(), url.scheme)
示例7: _request
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def _request(self, method, endpoint,
params=None, json=None, headers=None, timeout=None):
method = method.upper()
request_data = None
if headers:
self._update_headers(headers)
if json:
request_data = _json.dumps(json).encode('utf-8')
if self.unverified:
opener = urllib.build_opener(
HTTPSHandler(context=ssl._create_unverified_context()),
)
else:
opener = urllib.build_opener()
request = urllib.Request(self._build_url(endpoint, params), data=request_data)
if self.request_headers:
for key, value in self.request_headers.items():
request.add_header(key, value)
if request_data and ('Content-Type' not in self.request_headers):
request.add_header('Content-Type', 'application/json')
request.get_method = lambda: method
return Response(self._make_request(opener, request, timeout=timeout))
示例8: _download_via_urllib
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def _download_via_urllib(url, file_path, show_progress, disable_ssl_verification):
reporthook = None
if show_progress:
reporthook = _UrlRetrieveReportHook()
if disable_ssl_verification:
import ssl
# TODO: Remove this or properly implement disabling SSL certificate verification
orig_https_context = ssl._create_default_https_context #pylint: disable=protected-access
ssl._create_default_https_context = ssl._create_unverified_context #pylint: disable=protected-access
try:
urllib.request.urlretrieve(url, str(file_path), reporthook=reporthook)
finally:
# Try to reduce damage of hack by reverting original HTTPS context ASAP
if disable_ssl_verification:
ssl._create_default_https_context = orig_https_context #pylint: disable=protected-access
if show_progress:
print()
示例9: _create_connection
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def _create_connection(self, origin):
scheme, netloc = origin
if origin not in self.tls.conns:
proxy_config = self.server.proxy_config
kwargs = {
'timeout': self.timeout
}
if scheme == 'https':
connection = ProxyAwareHTTPSConnection
if not self.server.options.get('verify_ssl', False):
kwargs['context'] = ssl._create_unverified_context()
else:
connection = ProxyAwareHTTPConnection
self.tls.conns[origin] = connection(proxy_config, netloc, **kwargs)
return self.tls.conns[origin]
示例10: install_pip
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def install_pip():
try:
import pip # NOQA
except ImportError:
f = tempfile.NamedTemporaryFile(suffix='.py')
with contextlib.closing(f):
print("downloading %s to %s" % (GET_PIP_URL, f.name))
if hasattr(ssl, '_create_unverified_context'):
ctx = ssl._create_unverified_context()
else:
ctx = None
kwargs = dict(context=ctx) if ctx else {}
req = urlopen(GET_PIP_URL, **kwargs)
data = req.read()
f.write(data)
f.flush()
print("installing pip")
code = os.system('%s %s --user' % (PYTHON_EXE, f.name))
return code
示例11: open_url
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def open_url(self, url, headers = None):
# Fall back on the default ua if none provided
headers = self.ua if headers == None else headers
# Wrap up the try/except block so we don't have to do this for each function
try:
response = urlopen(Request(url, headers=headers))
except Exception as e:
if sys.version_info >= (3, 0) or not (isinstance(e, urllib2.URLError) and "CERTIFICATE_VERIFY_FAILED" in str(e)):
# Either py3, or not the right error for this "fix"
return None
# Py2 and a Cert verify error - let's set the unverified context
context = ssl._create_unverified_context()
try:
response = urlopen(Request(url, headers=headers), context=context)
except:
# No fixing this - bail
return None
return response
示例12: _process_provider_update
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def _process_provider_update(self):
"""Download provider update file from url"""
downloaded = False
updated = False
path = tempfile.gettempdir()
filename = os.path.join(path, 'provider-{}-update.txt'.format(self.config.name))
self._update_status('----Downloading providers update file----')
print('\n{}'.format(Status.message))
print('provider update url = ', self.config.provider_update_url)
try:
context = ssl._create_unverified_context()
urllib.urlretrieve(self.config.provider_update_url, filename, context=context)
downloaded = True
except Exception:
pass # fallback to no ssl context
if not downloaded:
try:
urllib.urlretrieve(self.config.provider_update_url, filename)
except Exception, e:
print('[e2m3u2b] process_provider_update error. Type:', type(e))
print('[e2m3u2b] process_provider_update error: ', e)
示例13: ip_adress_proxies
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def ip_adress_proxies(url='https://www.ip-adress.com/proxy_list/'):
# Downloading without proxy
opener = urllib.request.build_opener(urllib.request.ProxyHandler())
urllib.request.install_opener(opener)
request = urllib.request.Request(url)
request.add_header('user-agent', USER_AGENT)
parsed_uri = urlparse(url)
host = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
request.add_header('referer', host)
s = False
try:
context = ssl._create_unverified_context()
with urlopen(request, context=context, timeout=3000) as response:
s = response.read().decode('utf-8')
except Exception as er:
print(er)
pattern = r'\d*\.\d*\.\d*\.\d*\</a>:\d*'
found = [i.replace('</a>', '') + '\n' for i in re.findall(pattern, s)]
return found
示例14: make_request
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def make_request(url, with_proxy=False):
# original function
if url:
logger.debug(url)
if with_proxy:
return make_request_with_proxy(url)
try:
headers = get_rosreestr_headers()
request = Request(url, headers=headers)
context = ssl._create_unverified_context()
with urlopen(request, context=context, timeout=3000) as response:
read = response.read()
is_error = is_error_response(url, read)
if is_error:
raise Exception(is_error)
return read
except Exception as er:
logger.warning(er)
print(er)
# raise TimeoutException()
return False
示例15: upload_files_in_session
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_unverified_context [as 別名]
def upload_files_in_session(self, files_map, session_id):
for f_name, f_path in files_map.items():
file_spec = self.client.upload_file_service.AddSpec(name=f_name,
source_type=UpdateSessionFile.SourceType.PUSH,
size=os.path.getsize(f_path))
file_info = self.client.upload_file_service.add(session_id, file_spec)
# Upload the file content to the file upload URL
with open(f_path, 'rb') as local_file:
request = urllib2.Request(file_info.upload_endpoint.uri, local_file)
request.add_header('Cache-Control', 'no-cache')
request.add_header('Content-Length', '{0}'.format(os.path.getsize(f_path)))
request.add_header('Content-Type', 'text/ovf')
if self.skip_verification and hasattr(ssl, '_create_unverified_context'):
# Python 2.7.9 has stronger SSL certificate validation,
# so we need to pass in a context when dealing with
# self-signed certificates.
context = ssl._create_unverified_context()
urllib2.urlopen(request, context=context)
else:
# Don't pass context parameter since versions of Python
# before 2.7.9 don't support it.
urllib2.urlopen(request)