当前位置: 首页>>代码示例>>Python>>正文


Python ssl._create_unverified_context方法代码示例

本文整理汇总了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) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:23,代码来源:liberty_crawler.py

示例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 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:22,代码来源:data_loader.py

示例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() 
开发者ID:fpsw,项目名称:Servo,代码行数:24,代码来源:note.py

示例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)) 
开发者ID:fpsw,项目名称:Servo,代码行数:22,代码来源:sms.py

示例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) 
开发者ID:sprinkler,项目名称:rainmachine-developer-resources,代码行数:20,代码来源:netatmo-parser.py

示例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) 
开发者ID:riramar,项目名称:hsecscan,代码行数:26,代码来源:hsecscan.py

示例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)) 
开发者ID:Kyligence,项目名称:kylinpy,代码行数:27,代码来源:client.py

示例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() 
开发者ID:Eloston,项目名称:ungoogled-chromium,代码行数:19,代码来源:downloads.py

示例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] 
开发者ID:wkeeling,项目名称:selenium-wire,代码行数:22,代码来源:proxy2.py

示例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 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:22,代码来源:__main__.py

示例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 
开发者ID:corpnewt,项目名称:USBMap,代码行数:20,代码来源:downloader.py

示例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) 
开发者ID:su1s,项目名称:e2m3u2bouquet,代码行数:25,代码来源:e2m3u2bouquet.py

示例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 
开发者ID:rendrom,项目名称:rosreestr2coord,代码行数:21,代码来源:proxy_handling.py

示例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 
开发者ID:rendrom,项目名称:rosreestr2coord,代码行数:23,代码来源:utils.py

示例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) 
开发者ID:vmware,项目名称:vsphere-automation-sdk-python,代码行数:24,代码来源:cls_api_helper.py


注:本文中的ssl._create_unverified_context方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。