當前位置: 首頁>>代碼示例>>Python>>正文


Python ssl._create_default_https_context方法代碼示例

本文整理匯總了Python中ssl._create_default_https_context方法的典型用法代碼示例。如果您正苦於以下問題:Python ssl._create_default_https_context方法的具體用法?Python ssl._create_default_https_context怎麽用?Python ssl._create_default_https_context使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ssl的用法示例。


在下文中一共展示了ssl._create_default_https_context方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: retrieve_status_page

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_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: _download_via_urllib

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_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

示例3: _request

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def _request(url, json_decode=True):
    ssl._create_default_https_context = ssl._create_unverified_context
    req = urllib.request.Request(url)

    try:
        result = urllib.request.urlopen(req)
    except urllib.error.HTTPError as e:
        raise RuntimeError("HTTP error ({})".format(str(e.code)))
    except urllib.error.URLError as e:
        raise RuntimeError("URL error ({})".format(str(e.reason)))

    data = result.read()
    result.close()

    if json_decode:
        try:
            return json.JSONDecoder().decode(data.decode())
        except Exception as e:
            raise RuntimeError("API response has invalid JSON format ({})"
                               .format(str(e.reason)))

    return data.decode() 
開發者ID:nutti,項目名稱:Screencast-Keys,代碼行數:24,代碼來源:addon_updator.py

示例4: __init__

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def __init__(self, host, port=None, key_file=None, cert_file=None,
                     timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                     source_address=None, *, context=None,
                     check_hostname=None):
            super(HTTPSConnection, self).__init__(host, port, timeout,
                                                  source_address)
            self.key_file = key_file
            self.cert_file = cert_file
            if context is None:
                context = ssl._create_default_https_context()
            will_verify = context.verify_mode != ssl.CERT_NONE
            if check_hostname is None:
                check_hostname = context.check_hostname
            if check_hostname and not will_verify:
                raise ValueError("check_hostname needs a SSL context with "
                                 "either CERT_OPTIONAL or CERT_REQUIRED")
            if key_file or cert_file:
                context.load_cert_chain(cert_file, key_file)
            self._context = context
            self._check_hostname = check_hostname 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:22,代碼來源:client.py

示例5: loadUcsConfig

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def loadUcsConfig():
	from ConfigParser import SafeConfigParser

	configFile = os.path.join(os.path.dirname(__file__),"UcsConfig.cfg")
	parser = SafeConfigParser()
	parser.read(configFile)

	sslProtocol = parser.get('ssl_connection', 'ssl_protocol').strip('"')
	isVerifyCertificate = parser.getboolean('ssl_connection', 'verify_certificate')

	if not sys.version_info < (2, 6):
		from functools import partial
		import ssl

		sslProtocolDict = {'TLSv1': ssl.PROTOCOL_TLSv1}

		ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=sslProtocolDict[sslProtocol])

		if not sys.version_info < (2, 7, 9) and not isVerifyCertificate:
			ssl._create_default_https_context = ssl._create_unverified_context 
開發者ID:CiscoUcs,項目名稱:UcsPythonSDK,代碼行數:22,代碼來源:UcsBase.py

示例6: __init__

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def __init__(self):

        # Whether we already have a valid HTTP session with the remote server
        self.http_session_valid = False

        # PEP 476: verify HTTPS certificates by default (implemented from Python 2.7.9)
        # https://bugs.python.org/issue22417
        if sys.hexversion >= 0x02070900:
            import ssl
            ssl._create_default_https_context = ssl._create_unverified_context

        # https://mechanicalsoup.readthedocs.io/
        self.browser = mechanicalsoup.StatefulBrowser()

        # Set custom user agent header
        self.browser.set_user_agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36')

        self.searchurl = self.baseurl + 'einsteiger' #?lang={language}'
        self.accessurl = self.baseurl + 'register:showalleverfahrenstabellen?AKZ={number}&lang={language}'

        self.reference_pattern = re.compile('.*\?AKZ=(.+?)&.*') 
開發者ID:ip-tools,項目名稱:patzilla,代碼行數:23,代碼來源:dpmaregister.py

示例7: downloadFile

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def downloadFile(url, destination, x, y, z):

		url = Utils.qualifyURL(url, x, y, z)

		code = 0

		# monkey patching SSL certificate issue
		# DONT use it in a prod/sensitive environment
		ssl._create_default_https_context = ssl._create_unverified_context

		try:
			path, response = urllib.request.urlretrieve(url, destination)
			code = 200
		except urllib.error.URLError as e:
			if not hasattr(e, "code"):
				print(e)
				code = -1
			else:
				code = e.code

		return code 
開發者ID:AliFlux,項目名稱:MapTilesDownloader,代碼行數:23,代碼來源:utils.py

示例8: __init__

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def __init__(self, host, user, password, wine, use_ssl=False,
                 verify_ssl=False, port=80):
        super(oxcSERVER, self).__init__()
        self.host = host
        self.hostname = host
        self.wine = wine
        self.user = user
        self.password = password
        self.ssl = use_ssl
        self.verify_ssl = verify_ssl
        self.port = port

        self.dbg_track_num = 0

        if not verify_ssl and hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context 
開發者ID:OpenXenManager,項目名稱:openxenmanager,代碼行數:18,代碼來源:oxcSERVER.py

示例9: get_version

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def get_version():
    version = platform.python_version()

    if version >= '3':
        import urllib.request as openurl
    else:
        import urllib2 as openurl

    socket.setdefaulttimeout(1.2)
    ssl._create_default_https_context = ssl._create_unverified_context

    url = "https://service-qgphxt7y-1253970226.gz.apigw.tencentcs.com/release/client_daily_task"
    post_data = "{}"
    request = openurl.Request(data=post_data.encode("utf-8") if version >= '3' else post_data,
                              url=url) if version >= '3' else openurl.Request(url, data=post_data)
    response = json.loads(json.loads(openurl.urlopen(request).read().decode("utf-8")))
    release_version = response["version"]
    message = response["message"]
    release_version_list = release_version.split(".")
    local_version_list = __version__.split(".")
    for i in range(0, len(release_version_list)):
        if int(release_version_list[i]) > int(local_version_list[i]):
            return {"version": release_version, "message": message}

    return {} 
開發者ID:tencentyun,項目名稱:scfcli,代碼行數:27,代碼來源:daily_task.py

示例10: ensure_ca_load

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def ensure_ca_load():
	if ssl.create_default_context().cert_store_stats()['x509_ca'] == 0:
		if has_certifi:
			def create_certifi_context(purpose = ssl.Purpose.SERVER_AUTH, *, cafile = None, capath = None, cadata = None):
				return ssl.create_default_context(purpose, cafile = certifi.where())

			ssl._create_default_https_context = create_certifi_context

		else:
			print('%s[!]%s Python was unable to load any CA bundles. Additionally, the fallback %scertifi%s module is not available. Install it with %spip3 install certifi%s for TLS connection support.' % (Fore.RED, Fore.RESET, Fore.GREEN, Fore.RESET, Fore.GREEN, Fore.RESET))
			sys.exit(-1)


# parse image[:tag] | archive argument 
開發者ID:RoliSoft,項目名稱:WSL-Distribution-Switcher,代碼行數:16,代碼來源:utils.py

示例11: patch

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def patch():
    if hasattr(ssl, '_create_unverified_context'):
        # Python >=2.7.9
        ssl._create_default_https_context = ssl._create_unverified_context
    else:
        # Python <2.7.9
        ssl.wrap_socket = sslwrap(ssl.wrap_socket) 
開發者ID:rapid7,項目名稱:nexpose-client-python,代碼行數:9,代碼來源:sslfix.py

示例12: __init__

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def __init__(self, host, port=None, key_file=None, cert_file=None,
                     strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                     source_address=None, context=None):
            HTTPConnection.__init__(self, host, port, strict, timeout,
                                    source_address)
            self.key_file = key_file
            self.cert_file = cert_file
            if context is None:
                context = ssl._create_default_https_context()
            if key_file or cert_file:
                context.load_cert_chain(cert_file, key_file)
            self._context = context 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:14,代碼來源:httplib.py

示例13: _checkout

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def _checkout(self, local_dir):
        url = self.config.get("url")
        logger.info("Downloading...")
        user_agent = self.config.get("user-agent")
        if not self.config.get("verify_cert", True):
            import ssl

            ssl._create_default_https_context = ssl._create_unverified_context

        if user_agent and sys.version_info[0] >= 3:
            opener = urllib.build_opener()
            opener.addheaders = [("User-agent", user_agent)]
            urllib.install_opener(opener)
        try:
            (filename, headers) = urllib.urlretrieve(url)
        except (URLError, HTTPError) as e:
            raise RuntimeError("Failed to download '{}'. '{}'".format(url, e.reason))

        filetype = self.config.get("filetype")
        if filetype == "tar":
            t = tarfile.open(filename)
            t.extractall(local_dir)
        elif filetype == "zip":
            with zipfile.ZipFile(filename, "r") as z:
                z.extractall(local_dir)
        elif filetype == "simple":
            _filename = url.rsplit("/", 1)[1]
            os.makedirs(local_dir)
            shutil.copy2(filename, os.path.join(local_dir, _filename))
        else:
            raise RuntimeError(
                "Unknown file type '" + filetype + "' in [provider] section"
            ) 
開發者ID:olofk,項目名稱:fusesoc,代碼行數:35,代碼來源:url.py

示例14: invoke_ssl_no_verify

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def invoke_ssl_no_verify():
    try:
        _create_unverified_https_context = ssl._create_unverified_context
        
    except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
        pass
    else:
    # Handle target environment that doesn't support HTTPS verification
        ssl._create_default_https_context = _create_unverified_https_context 
開發者ID:jeorryb,項目名稱:netapp-ansible,代碼行數:12,代碼來源:ntap_util.py

示例15: __init__

# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import _create_default_https_context [as 別名]
def __init__(self, cloud_info, inf):
        self.cloud = cloud_info
        """Data about the Cloud Provider."""
        self.inf = inf
        """Infrastructure this CloudConnector is associated with."""
        self.logger = logging.getLogger('CloudConnector')
        """Logger object."""
        self.error_messages = ""
        """String with error messages to be shown to the user."""
        self.verify_ssl = Config.VERIFI_SSL
        """Verify SSL connections """
        if not self.verify_ssl:
            # To avoid errors with host certificates
            try:
                import ssl
                ssl._create_default_https_context = ssl._create_unverified_context
            except Exception:
                pass

            try:
                # To avoid annoying InsecureRequestWarning messages in some Connectors
                import requests.packages
                from requests.packages.urllib3.exceptions import InsecureRequestWarning
                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            except Exception:
                pass 
開發者ID:grycap,項目名稱:im,代碼行數:28,代碼來源:CloudConnector.py


注:本文中的ssl._create_default_https_context方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。