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


Python certifi.where方法代碼示例

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


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

示例1: fetch_service_config_rollout_strategy

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def fetch_service_config_rollout_strategy(metadata):
    """Fetch service config rollout strategy from metadata URL."""
    url = metadata + _METADATA_PATH + "/attributes/" + \
        _METADATA_ROLLOUT_STRATEGY
    headers = {"Metadata-Flavor": "Google"}
    client = urllib3.PoolManager(ca_certs=certifi.where())
    try:
        response = client.request("GET", url, headers=headers)
    except:
        logging.info("Failed to fetch service config rollout strategy " + \
            "from the metadata server: " + url);
        return None
    status_code = response.status

    if status_code != 200:
        # Fetching rollout strategy is optional. No need to leave log
        return None

    rollout_strategy = response.data
    logging.info("Service config rollout strategy: " + rollout_strategy)
    return rollout_strategy 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:23,代碼來源:fetch_service_config.py

示例2: fetch_service_name

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def fetch_service_name(metadata):
    """Fetch service name from metadata URL."""
    url = metadata + _METADATA_PATH + "/attributes/" + _METADATA_SERVICE_NAME
    headers = {"Metadata-Flavor": "Google"}
    client = urllib3.PoolManager(ca_certs=certifi.where())
    try:
        response = client.request("GET", url, headers=headers)
    except:
        raise FetchError(1,
            "Failed to fetch service name from the metadata server: " + url)
    status_code = response.status

    if status_code != 200:
        message_template = "Fetching service name failed (url {}, status code {})"
        raise FetchError(1, message_template.format(url, status_code))

    name = response.data
    logging.info("Service name: " + name)
    return name

# config_id from metadata is optional. Returns None instead of raising error 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:23,代碼來源:fetch_service_config.py

示例3: fetch_access_token

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def fetch_access_token(metadata):
    """Fetch access token from metadata URL."""
    access_token_url = metadata + _METADATA_PATH + "/service-accounts/default/token"
    headers = {"Metadata-Flavor": "Google"}
    client = urllib3.PoolManager(ca_certs=certifi.where())
    try:
        response = client.request("GET", access_token_url, headers=headers)
    except:
        raise FetchError(1,
            "Failed to fetch access token from the metadata server: " + access_token_url)
    status_code = response.status

    if status_code != 200:
        message_template = "Fetching access token failed (url {}, status code {})"
        raise FetchError(1, message_template.format(access_token_url, status_code))

    token = json.loads(response.data)["access_token"]
    return token 
開發者ID:cloudendpoints,項目名稱:endpoints-tools,代碼行數:20,代碼來源:fetch_service_config.py

示例4: _fill_in_cainfo

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def _fill_in_cainfo(self):
        """Fill in the path of the PEM file containing the CA certificate.

        The priority is: 1. user provided path, 2. path to the cacert.pem
        bundle provided by certifi (if installed), 3. let pycurl use the
        system path where libcurl's cacert bundle is assumed to be stored,
        as established at libcurl build time.
        """
        if self.cainfo:
            cainfo = self.cainfo
        else:
            try:
                cainfo = certifi.where()
            except AttributeError:
                cainfo = None
        if cainfo:
            self._pycurl.setopt(pycurl.CAINFO, cainfo) 
開發者ID:shichao-an,項目名稱:homura,代碼行數:19,代碼來源:homura.py

示例5: _certifi_ssl_context

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def _certifi_ssl_context(self):
        if (sys.version_info.major == 2 and sys.hexversion >= 0x02070900 or
           sys.version_info.major == 3 and sys.hexversion >= 0x03040300):
            where = certifi.where()
            self._log(DEBUG1, 'certifi %s: %s', certifi.__version__, where)
            return ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH,
                cafile=where)
        else:
            return None


#
# XXX USE OF cloud_ssl_context() IS DEPRECATED!
#
# If your operating system certificate store is out of date you can
# install certifi (https://pypi.python.org/pypi/certifi) and its CA
# bundle will be used for SSL server certificate verification when
# ssl_context is None.
# 
開發者ID:PaloAltoNetworks,項目名稱:terraform-templates,代碼行數:22,代碼來源:wfapi.py

示例6: aiohttp_session

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def aiohttp_session(*, auth: Optional[Auth] = None, **kwargs: Any) -> ClientSession:
    headers = {'User-Agent': USER_AGENT}
    if auth:
        headers['Authorization'] = auth.encode()

    # setup SSL
    cafile = config.get('ca')
    if not cafile:
        cafile = certifi.where()
    ssl_context = create_default_context(cafile=cafile)
    try:
        connector = TCPConnector(ssl=ssl_context)
    except TypeError:
        connector = TCPConnector(ssl_context=ssl_context)

    return ClientSession(headers=headers, connector=connector, **kwargs) 
開發者ID:dephell,項目名稱:dephell,代碼行數:18,代碼來源:networking.py

示例7: set_tlsio

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def set_tlsio(self, hostname, port):
        """Setup the default underlying TLS IO layer. On Windows this is
        Schannel, on Linux and MacOS this is OpenSSL.

        :param hostname: The endpoint hostname.
        :type hostname: bytes
        :param port: The TLS port.
        :type port: int
        """
        _default_tlsio = c_uamqp.get_default_tlsio()
        _tlsio_config = c_uamqp.TLSIOConfig()
        _tlsio_config.hostname = hostname
        _tlsio_config.port = int(port)

        _underlying_xio = c_uamqp.xio_from_tlsioconfig(_default_tlsio, _tlsio_config) # pylint: disable=attribute-defined-outside-init

        cert = self.cert_file or certifi.where()
        with open(cert, 'rb') as cert_handle:
            cert_data = cert_handle.read()
            try:
                _underlying_xio.set_certificates(cert_data)
            except ValueError:
                _logger.warning('Unable to set external certificates.')
        self.sasl_client = _SASLClient(_underlying_xio, self.sasl) # pylint: disable=attribute-defined-outside-init
        self.consumed = False # pylint: disable=attribute-defined-outside-init 
開發者ID:Azure,項目名稱:azure-uamqp-python,代碼行數:27,代碼來源:common.py

示例8: request

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def request(url, data=None, headers={}, cookies={}, auth=None):
 if cookies:
  headers['Cookie'] = '; '.join(quote(k) + '=' + quote(v) for (k, v) in cookies.items())
 request = Request(str(url), data, headers)
 manager = HTTPPasswordMgrWithDefaultRealm()
 if auth:
  manager.add_password(None, request.get_full_url(), auth[0], auth[1])
 handlers = [HTTPBasicAuthHandler(manager), HTTPDigestAuthHandler(manager)]
 try:
  import certifi, ssl
  handlers.append(HTTPSHandler(context=ssl.create_default_context(cafile=certifi.where())))
 except:
  # App engine
  pass
 response = build_opener(*handlers).open(request)
 cj = CookieJar()
 cj.extract_cookies(response, request)
 headers = dict(response.headers)
 raw_contents = response.read()
 contents = raw_contents.decode(headers.get('charset', 'latin1'))
 return HttpResponse(urlparse(response.geturl()), contents, raw_contents, headers, dict((c.name, c.value) for c in cj)) 
開發者ID:ma1co,項目名稱:Sony-PMCA-RE,代碼行數:23,代碼來源:http.py

示例9: __init__

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def __init__(self, tor_controller=None):
        if not self.__socket_is_patched():
            gevent.monkey.patch_socket()
        self.tor_controller = tor_controller
        if not self.tor_controller:
            retries = urllib3.Retry(35)
            user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
            self.session = urllib3.PoolManager(maxsize=35,
                                               cert_reqs='CERT_REQUIRED',
                                               ca_certs=certifi.where(),
                                               headers=user_agent,
                                               retries=retries)
        else:
            self.session = self.tor_controller.get_tor_session()
        self.__tor_status__()
        self.languages = self._get_all_languages() 
開發者ID:SekouD,項目名稱:mlconjug,代碼行數:18,代碼來源:cooljugator_scraper.py

示例10: pageRequest

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def pageRequest(url):
    global roundRobin
    proxy = SOCKSProxyManager('socks5://localhost:'+str(torPort),
        cert_reqs='CERT_REQUIRED',
        ca_certs=certifi.where(),
        headers={'user-agent': randomUserAgent(), 'Cookie': ''})
    http = urllib3.PoolManager( 1,
        cert_reqs='CERT_REQUIRED',
        ca_certs=certifi.where(),
        headers={'user-agent': randomUserAgent(), 'Cookie': ''})
    if roundRobin % 2:
        response = http.request('GET', url)
    else:
        if torSupport:
            response = proxy.request('GET', url)
        else:
            response = http.request('GET', url)
    roundRobin += 1
    if not roundRobin % 60:
        newTorIdentity()
    return response.data 
開發者ID:pielco11,項目名稱:JungleScam,代碼行數:23,代碼來源:junglescam.py

示例11: _get_default_ssl_context

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def _get_default_ssl_context(self) -> '_ssl.SSLContext':
        if _ssl is None:
            raise RuntimeError('SSL is not supported.')

        try:
            import certifi
        except ImportError:
            cafile = None
        else:
            cafile = certifi.where()

        ctx = _ssl.create_default_context(
            purpose=_ssl.Purpose.SERVER_AUTH,
            cafile=cafile,
        )
        ctx.options |= (_ssl.OP_NO_TLSv1 | _ssl.OP_NO_TLSv1_1)
        ctx.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20')
        ctx.set_alpn_protocols(['h2'])
        try:
            ctx.set_npn_protocols(['h2'])
        except NotImplementedError:
            pass

        return ctx 
開發者ID:vmagamedov,項目名稱:grpclib,代碼行數:26,代碼來源:client.py

示例12: where

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def where():
        cacert_pem = IkaUtils.get_path('cacert.pem')
        if os.path.exists(cacert_pem):
            return cacert_pem

        try:
            import certifi
            cacert_pem = certifi.where()
            if os.path.exists(cacert_pem):
                return cacert_pem
        except ImportError:
            pass

        try:
            import requests.certs
            cacert_pem = requests.certs.where()
            if os.path.exists(cacert_pem):
                return cacert_pem
        except ImportError:
            pass

        IkaUtils.dprint('ikalog.utils.Certifi: Cannot find any cacert.pem')

        return None 
開發者ID:hasegaw,項目名稱:IkaLog,代碼行數:26,代碼來源:certifi.py

示例13: __init__

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def __init__(self, **kwds):
        for key in kwds:
            self.__dict__[key] = kwds[key]

        log.warn("APIClient: This APIClient will be removed in a future version of this package.  Please"
                 "migrate away as soon as possible.")

        if "INSTANA_API_TOKEN" in os.environ:
            self.api_token = os.environ["INSTANA_API_TOKEN"]

        if "INSTANA_BASE_URL" in os.environ:
            self.base_url = os.environ["INSTANA_BASE_URL"]

        if self.base_url is None or self.api_token is None:
            log.warn("APIClient: API token or Base URL not set.  No-op mode")
        else:
            self.api_key = "apiToken %s" % self.api_token
            self.headers = {'Authorization': self.api_key, 'User-Agent': 'instana-python-sensor v' + package_version()}
            self.http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
                                            ca_certs=certifi.where()) 
開發者ID:instana,項目名稱:python-sensor,代碼行數:22,代碼來源:api.py

示例14: connect

# 需要導入模塊: import certifi [as 別名]
# 或者: from certifi import where [as 別名]
def connect(block=False):
    global block_loop
    block_loop = block
    global current_subscribe_list
    global current_id
    times = 1
    while not microgear.accesstoken:
        get_token()
        time.sleep(times)
        times = times+10
    microgear.mqtt_client = mqtt.Client(microgear.accesstoken["token"])
    current_id = '/&id/'+str(microgear.accesstoken["token"])+'/#'
    current_subscribe_list.append('/&id/'+str(microgear.accesstoken["token"])+'/#')
    endpoint = microgear.accesstoken["endpoint"].split("//")[1].split(":")
    username = microgear.gearkey+"%"+str(int(time.time()))
    password = hmac(microgear.accesstoken["secret"]+"&"+microgear.gearsecret,microgear.accesstoken["token"]+"%"+username)
    microgear.mqtt_client.username_pw_set(username,password)
    if microgear.securemode:
        microgear.mqtt_client.tls_set(certifi.where())
        microgear.mqtt_client.connect(endpoint[0],int(microgear.gbsport), 60)
    else:
        microgear.mqtt_client.connect(endpoint[0],int(microgear.gbport), 60)
    microgear.mqtt_client.on_connect = client_on_connect
    microgear.mqtt_client.on_message = client_on_message
    microgear.mqtt_client.on_publish = client_on_publish
    microgear.mqtt_client.on_subscribe = client_on_subscribe
    microgear.mqtt_client.on_disconnect = client_on_disconnect

    if(block):
        microgear.mqtt_client.loop_forever()
    else:
        microgear.mqtt_client.loop_start()
        while True:
            time.sleep(2)
            break 
開發者ID:netpieio,項目名稱:microgear-python,代碼行數:37,代碼來源:client.py

示例15: ensure_ca_load

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


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