How to use the urllib3.exceptions function in urllib3

To help you get started, we’ve selected a few urllib3 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 python-trio / hip / test / appengine / test_gae_manager.py View on Github external
def test_exceptions(self):
        # SSLCertificateError -> SSLError
        # SSLError is raised with dummyserver because URLFetch doesn't allow
        # self-signed certs.
        with pytest.raises(urllib3.exceptions.SSLError):
            self.pool.request("GET", "/")
github mesosphere / dcos-kafka-service / testing / sdk_cmd.py View on Github external
import sdk_utils


log = logging.getLogger(__name__)

DEFAULT_TIMEOUT_SECONDS = 30 * 60
SSH_USERNAME = os.environ.get("DCOS_SSH_USERNAME", "core")
SSH_KEY_FILE = os.environ.get("DCOS_SSH_KEY_FILE", "")

# Silence this warning. We expect certs to be self-signed:
# /usr/local/lib/python3.6/dist-packages/urllib3/connectionpool.py:857:
#     InsecureRequestWarning: Unverified HTTPS request is being made.
#     Adding certificate verification is strongly advised.
#     See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def service_request(
    method,
    service_name,
    service_path,
    retry=True,
    raise_on_error=True,
    log_args=True,
    log_response=False,
    timeout_seconds=60,
    **kwargs,
):
    """Used to query a service running on the cluster. See `cluster_request()` for arg meanings.
    : param service_name: The name of the service, e.g. 'marathon' or 'hello-world'
    : param service_path: HTTP path to be queried against the service, e.g. '/v2/apps'. Leading slash is optional.
github SpiderLabs / HostHunter / hosthunter.py View on Github external
def sslGrabber(hostx,port):
    try:
        cert=ssl.get_server_certificate((hostx.address, port))
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        cert_hostname=x509.get_subject().CN
        # Add New HostNames to List
        if cert_hostname is not None:
            for host in cert_hostname.split('\n'):
                if (host=="") or (host in hostx.hname):
                    pass
                else:
                    hostx.hname.append(host)
    except (urllib3.exceptions.ReadTimeoutError,requests.ConnectionError,urllib3.connection.ConnectionError,urllib3.exceptions.MaxRetryError,urllib3.exceptions.ConnectTimeoutError,urllib3.exceptions.TimeoutError,socket.error,socket.timeout) as e:
        pass
github tbalz2319 / RapidRepoPull / rapid.py View on Github external
import os
import sys
import click
from termcolor import colored
import traceback
import subprocess
import queue
import threading
import multiprocessing
import giturlparse
import urllib3
from bs4 import BeautifulSoup
import re
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from huepy import *

# When acquired by a thread it locks other threads from printing
lock = threading.Lock()
stop = 0

# Function to handle processing of commands
def subprocess_cmd(command):
    # The actual name of the repo is pulled from the url in order to display it to the user
    name = command[2].split("/")[-1].replace(".git", "")

    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()

    lock.acquire()
    if "fatal".encode("utf-8") not in err:
github influxdata / influxdb-client-python / influxdb2 / rest.py View on Github external
timeout=timeout,
                        headers=headers)
                else:
                    # Cannot generate the request from given parameters
                    msg = """Cannot prepare a request message for provided
                             arguments. Please check that your arguments match
                             declared content type."""
                    raise ApiException(status=0, reason=msg)
            # For `GET`, `HEAD`
            else:
                r = self.pool_manager.request(method, url,
                                              fields=query_params,
                                              preload_content=_preload_content,
                                              timeout=timeout,
                                              headers=headers)
        except urllib3.exceptions.SSLError as e:
            msg = "{0}\n{1}".format(type(e).__name__, str(e))
            raise ApiException(status=0, reason=msg)

        if _preload_content:
            r = RESTResponse(r)

            # In the python 3, the response.data is bytes.
            # we need to decode it to string.
            if six.PY3:
                r.data = r.data.decode('utf8')

            # log response body
            logger.debug("response body: %s", r.data)

        if not 200 <= r.status <= 299:
            raise ApiException(http_resp=r)
github tribe29 / checkmk / cmk / special_agents / agent_jira.py View on Github external
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

import argparse
import json
import logging
import sys
from typing import Any, Dict, Union

from requests.exceptions import ConnectionError as RequestsConnectionError
import urllib3  # type: ignore[import]
from jira import JIRA  # type: ignore[import]
from jira.exceptions import JIRAError  # type: ignore[import]

urllib3.disable_warnings(urllib3.exceptions.SubjectAltNameWarning)


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    args = parse_arguments(argv)
    setup_logging(args.verbose)

    try:
        logging.info('Start constructing connection settings')
        jira = _handle_jira_connection(args)
    except RequestsConnectionError as connection_error:
        sys.stderr.write("Error connecting Jira server: %s\n" % connection_error)
        if args.debug:
            raise
github cungnv / scrapex / scrapex / http.py View on Github external
from . import (common, agent)
from .node import Node
from .proxy import (ProxyManager, Proxy)
from .doc import Doc

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

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


meta_seperator = '=======META======'

logger = logging.getLogger(__name__)



class Request(object):  
	""" Represents a http request """

	def __init__(self, url, **options):        
		
		self.url = url.replace(' ', '%20')
		
		self.options = options
github ansibleplaybookbundle / ansible-playbook-bundle / src / apb / engine.py View on Github external
from openshift import client as openshift_client, config as openshift_config
from openshift.helper.openshift import OpenShiftObjectHelper
from jinja2 import Environment, FileSystemLoader
from kubernetes import client as kubernetes_client, config as kubernetes_config
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream as kubernetes_stream
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# Handle input in 2.x/3.x
try:
    input = raw_input
except NameError:
    pass

# Disable insecure request warnings from both packages
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

ROLES_DIR = 'roles'

DAT_DIR = 'dat'
DAT_PATH = os.path.join(os.path.dirname(__file__), DAT_DIR)

SPEC_FILE = 'apb.yml'
EX_SPEC_FILE = 'apb.yml.j2'
EX_SPEC_FILE_PATH = os.path.join(DAT_PATH, EX_SPEC_FILE)
SPEC_FILE_PARAM_OPTIONS = ['name', 'description', 'type', 'default']

DOCKERFILE = 'Dockerfile'
EX_DOCKERFILE = 'Dockerfile.j2'
EX_DOCKERFILE_PATH = os.path.join(DAT_PATH, EX_DOCKERFILE)
github praekelt / feersum-nlu-api-wrappers / examples / sentiment_detector.py View on Github external
api_instance = feersum_nlu.SentimentDetectorsApi(feersum_nlu.ApiClient(configuration))

model_instance_name = 'generic'
text_input = feersum_nlu.TextInput("I am very happy. I am not happy.")

print()

try:
    print("Detect sentiment:")
    api_response = api_instance.sentiment_detector_retrieve(model_instance_name, text_input)
    print(" type(api_response)", type(api_response))
    print(" api_response", api_response)
    print()
except ApiException as e:
    print("Exception when calling SentimentDetectorsApi->sentiment_detector_retrieve: %s\n" % e)
except urllib3.exceptions.HTTPError as e:
    print("Connection HTTPError! %s\n" % e)
github jay0lee / GAM / src / google / auth / transport / urllib3.py View on Github external
google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """
        # urllib3 uses a sentinel default value for timeout, so only set it if
        # specified.
        if timeout is not None:
            kwargs['timeout'] = timeout

        try:
            _LOGGER.debug('Making request: %s %s', method, url)
            response = self.http.request(
                method, url, body=body, headers=headers, **kwargs)
            return _Response(response)
        except urllib3.exceptions.HTTPError as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc)