Python源码示例:certifi.where()
示例1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
示例16
def where():
"""Return the preferred certificate bundle."""
# vendored bundle inside Requests
return os.path.join(os.path.dirname(__file__), 'cacert.pem')
示例17
def fetch_service_config_id(metadata):
"""Fetch service config ID from metadata URL."""
url = metadata + _METADATA_PATH + "/attributes/" + _METADATA_SERVICE_CONFIG_ID
headers = {"Metadata-Flavor": "Google"}
client = urllib3.PoolManager(ca_certs=certifi.where())
try:
response = client.request("GET", url, headers=headers)
if response.status != 200:
# Fetching service config id is optional. No need to leave log
raise None
except:
url = metadata + _METADATA_PATH + "/attributes/endpoints-service-version"
try:
response = client.request("GET", url, headers=headers)
except:
logging.info("Failed to fetch service config ID from the metadata server: " + url)
return None
if response.status != 200:
message_template = "Fetching service config ID failed (url {}, status code {})"
logging.info(message_template.format(url, response.status))
return None
version = response.data
logging.info("Service config ID:" + version)
return version
示例18
def fetch_latest_rollout(management_service, service_name, access_token):
"""Fetch rollouts"""
if access_token is None:
headers = {}
else:
headers = {"Authorization": "Bearer {}".format(access_token)}
client = urllib3.PoolManager(ca_certs=certifi.where())
service_mgmt_url = SERVICE_MGMT_ROLLOUTS_URL_TEMPLATE.format(management_service,
service_name)
try:
response = client.request("GET", service_mgmt_url, headers=headers)
except:
raise FetchError(1, "Failed to fetch rollouts")
status_code = response.status
if status_code != 200:
message_template = ("Fetching rollouts failed "\
"(status code {}, reason {}, url {})")
raise FetchError(1, message_template.format(status_code,
response.reason,
service_mgmt_url))
rollouts = json.loads(response.data)
# No valid rollouts
if rollouts is None or \
'rollouts' not in rollouts or \
len(rollouts["rollouts"]) == 0 or \
"rolloutId" not in rollouts["rollouts"][0] or \
"trafficPercentStrategy" not in rollouts["rollouts"][0] or \
"percentages" not in rollouts["rollouts"][0]["trafficPercentStrategy"]:
message_template = ("Invalid rollouts response (url {}, data {})")
raise FetchError(1, message_template.format(service_mgmt_url,
response.data))
return rollouts["rollouts"][0]
示例19
def __init__(self, repo_name=None):
self.repo_name = repo_name
self.credentials = load_credentials()
self.base_url = self.credentials['artifactory_url']
self.artifactory = party.Party()
if not self.base_url.endswith('/api'):
self.api_url = '/'.join([self.base_url, 'api'])
else:
self.api_url = self.base_url
self.artifactory.artifactory_url = self.api_url
self.artifactory.username = self.credentials['artifactory_username']
self.artifactory.password = base64.encodebytes(bytes(self.credentials['artifactory_password'], 'utf-8'))
self.artifactory.certbundle = os.getenv('LAVATORY_CERTBUNDLE_PATH', certifi.where())
示例20
def where():
env = os.environ.get("HTTPLIB2_CA_CERTS")
if env is not None:
if os.path.isfile(env):
return env
else:
raise RuntimeError("Environment variable HTTPLIB2_CA_CERTS not a valid file")
if custom_ca_locater_available:
return custom_ca_locater_where()
if certifi_available:
return certifi_where()
return BUILTIN_CA_CERTS
示例21
def where():
env = os.environ.get("HTTPLIB2_CA_CERTS")
if env is not None:
if os.path.isfile(env):
return env
else:
raise RuntimeError("Environment variable HTTPLIB2_CA_CERTS not a valid file")
if custom_ca_locater_available:
return custom_ca_locater_where()
if certifi_available:
return certifi_where()
return BUILTIN_CA_CERTS
示例22
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
"""Resolves an address.
The ``host`` argument is a string which may be a hostname or a
literal IP address.
Returns a `.Future` whose result is a list of (family,
address) pairs, where address is a tuple suitable to pass to
`socket.connect <socket.socket.connect>` (i.e. a ``(host,
port)`` pair for IPv4; additional fields may be present for
IPv6). If a ``callback`` is passed, it will be run with the
result as an argument when it is complete.
"""
raise NotImplementedError()
示例23
def _default_ca_certs():
if certifi is None:
raise Exception("The 'certifi' package is required to use https "
"in simple_httpclient")
return certifi.where()
示例24
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
"""Resolves an address.
The ``host`` argument is a string which may be a hostname or a
literal IP address.
Returns a `.Future` whose result is a list of (family,
address) pairs, where address is a tuple suitable to pass to
`socket.connect <socket.socket.connect>` (i.e. a ``(host,
port)`` pair for IPv4; additional fields may be present for
IPv6). If a ``callback`` is passed, it will be run with the
result as an argument when it is complete.
"""
raise NotImplementedError()
示例25
def _default_ca_certs():
if certifi is None:
raise Exception("The 'certifi' package is required to use https "
"in simple_httpclient")
return certifi.where()
示例26
def where():
"""Return the preferred certificate bundle."""
# vendored bundle inside Requests
return os.path.join(os.path.dirname(__file__), 'cacert.pem')
示例27
def where():
"""Return the preferred certificate bundle."""
# vendored bundle inside Requests
return os.path.join(os.path.dirname(__file__), 'cacert.pem')
示例28
def where():
"""Return the preferred certificate bundle."""
# vendored bundle inside Requests
return os.path.join(os.path.dirname(__file__), 'cacert.pem')
示例29
def __init__(self, api_key, cartodb_domain, host='carto.com', protocol='https', proxy_info=None, *args, **kwargs):
super(CartoDBAPIKey, self).__init__(cartodb_domain, host, protocol, *args, **kwargs)
self.api_key = api_key
certificate_location = certifi.where()
self.client = httplib2.Http(ca_certs=certificate_location)
if protocol != 'https':
warnings.warn("you are using API key auth method with http")
示例30
def where():
"""Return the preferred certificate bundle."""
# vendored bundle inside Requests
return os.path.join(os.path.dirname(__file__), 'cacert.pem')