本文整理汇总了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
示例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
示例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
示例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)
示例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.
#
示例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)
示例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
示例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))
示例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()
示例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
示例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
示例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
示例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())
示例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
示例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