How to use certifi - 10 common examples

To help you get started, we’ve selected a few certifi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cpbotha / nvpy / nvpy / nvpy.py View on Github external
def get_appdir():
    # setup appdir
    if hasattr(sys, 'frozen') and sys.frozen:
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller
            appdir = sys._MEIPASS

            # WORKAROUND: Bug that always raise the SSLCertVerificationError from urlopen()
            #             when CPython is not installed.

            # Use certificate from certifi only if cafile could not find by ssl.
            # See https://github.com/pyinstaller/pyinstaller/pull/3952
            import ssl
            if ssl.get_default_verify_paths().cafile is None:
                import certifi
                os.environ['SSL_CERT_FILE'] = certifi.core.where()
        else:
            # py2exe
            appdir, _ = os.path.split(sys.executable)

    else:
        dirname, _ = os.path.split(os.path.realpath(__file__))
        if dirname and dirname != os.curdir:
            appdir = dirname
        else:
            appdir = os.getcwd()

    # make sure it's the full path
    appdir_full_path = os.path.abspath(appdir)
    return appdir_full_path
github cloudendpoints / esp / start_esp / fetch_service_config.py View on Github external
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.data,
                                                    service_mgmt_url))
    rollouts = json.loads(response.data)
github yapily / yapily-sdk-python / sdk / yapily / rest.py View on Github external
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680  # noqa: E501
        # maxsize is the number of requests to host that are allowed in parallel  # noqa: E501
        # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html  # noqa: E501

        # cert_reqs
        if configuration.verify_ssl:
            cert_reqs = ssl.CERT_REQUIRED
        else:
            cert_reqs = ssl.CERT_NONE

        # ca_certs
        if configuration.ssl_ca_cert:
            ca_certs = configuration.ssl_ca_cert
        else:
            # if not set certificate file, use Mozilla's root certificates.
            ca_certs = certifi.where()

        addition_pool_args = {}
        if configuration.assert_hostname is not None:
            addition_pool_args['assert_hostname'] = configuration.assert_hostname  # noqa: E501

        if configuration.retries is not None:
            addition_pool_args['retries'] = configuration.retries

        if maxsize is None:
            if configuration.connection_pool_maxsize is not None:
                maxsize = configuration.connection_pool_maxsize
            else:
                maxsize = 4

        # https pool manager
        if configuration.proxy:
github olitheolix / aiokubernetes / aiokubernetes / api_client.py View on Github external
self.default_headers = {}
        if header_name is not None:
            self.default_headers[header_name] = header_value
        self.cookie = cookie

        # Set default User-Agent.
        self.user_agent = 'Swagger-Codegen/1.0/python'

        self.configuration = configuration

        # ca_certs
        if configuration.ssl_ca_cert:
            ca_certs = configuration.ssl_ca_cert
        else:
            # if not set certificate file, use Mozilla's root certificates.
            ca_certs = certifi.where()

        ssl_context = ssl.create_default_context(cafile=ca_certs)
        if configuration.cert_file:
            ssl_context.load_cert_chain(
                configuration.cert_file, keyfile=configuration.key_file
            )

        connector = aiohttp.TCPConnector(
            limit=4,
            ssl_context=ssl_context,
            verify_ssl=configuration.verify_ssl
        )

        # https pool manager
        self.session = aiohttp.ClientSession(connector=connector)
github R0uter / gfw_domain_whitelist / main.py View on Github external
def getList(listUrl):
    http = urllib3.PoolManager(
        cert_reqs='CERT_REQUIRED',  # Force certificate check.
        ca_certs=certifi.where(),  # Path to the Certifi bundle.
    )

    data = http.request('GET', listUrl, timeout=10).data
    return data
github mistio / mist-ce / docker / elasticsearch-manage / scripts / add_templates.py View on Github external
def es_client():
    es = Elasticsearch(
        os.getenv('ELASTIC_HOST', 'elasticsearch'),
        port=os.getenv('ELASTIC_PORT', '9200'),
        http_auth=(os.getenv('ELASTIC_USER', ''),
                   os.getenv('ELASTIC_PASSWORD', '')),
        use_ssl=bool(os.getenv('ELASTIC_SSL', False)),
        verify_certs=bool(os.getenv('ELASTIC_VERIFY_CERTS', False)),
        ca_certs=certifi.where()
    )
    for i in range(20):
        if es.ping():
            return es
        print("Elasticsearch not up yet")
        time.sleep(1)
    print("Elasticsearch doesn't respond to ping")
    raise Exception()
github Azure / azure-cli / src / command_modules / azure-cli-appservice / azure / cli / command_modules / appservice / custom.py View on Github external
def _get_log(url, user_name, password, log_file=None):
    import certifi
    import urllib3
    try:
        import urllib3.contrib.pyopenssl
        urllib3.contrib.pyopenssl.inject_into_urllib3()
    except ImportError:
        pass

    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
    headers = urllib3.util.make_headers(basic_auth='{0}:{1}'.format(user_name, password))
    r = http.request(
        'GET',
        url,
        headers=headers,
        preload_content=False
    )
    if r.status != 200:
        raise CLIError("Failed to connect to '{}' with status code '{}' and reason '{}'".format(
            url, r.status, r.reason))
    if log_file:  # download logs
        with open(log_file, 'wb') as f:
            while True:
                data = r.read(1024)
                if not data:
                    break
github intercom / python-intercom / intercom / request.py View on Github external
if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Sending %s request to: %s", self.http_method, url)
            logger.debug("  headers: %s", headers)
            if self.http_method == 'GET':
                logger.debug("  params: %s", req_params['params'])
            else:
                logger.debug("  params: %s", req_params['data'])

        if self.http_session is None:
            resp = requests.request(
                self.http_method, url, timeout=self.timeout,
                auth=auth, verify=certifi.where(), **req_params)
        else:
            resp = self.http_session.request(
                self.http_method, url, timeout=self.timeout,
                auth=auth, verify=certifi.where(), **req_params)

        # response logging
        if logger.isEnabledFor(logging.DEBUG):
            logger.debug("Response received from %s", url)
            logger.debug("  encoding=%s status:%s",
                         resp.encoding, resp.status_code)
            logger.debug("  content:\n%s", resp.content)

        parsed_body = self.parse_body(resp)
        self.raise_errors_on_failure(resp)
        self.set_rate_limit_details(resp)
        return parsed_body

certifi

Python package for providing Mozilla's CA Bundle.

MPL-2.0
Latest version published 20 days ago

Package Health Score

89 / 100
Full package analysis

Similar packages