Python six.moves.http_client.HTTPSConnection() Examples

The following are 20 code examples of six.moves.http_client.HTTPSConnection(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six.moves.http_client , or try the search function .
Example #1
Source File: runner.py    From canari3 with GNU General Public License v3.0 6 votes vote down vote up
def remote_canari_transform_runner(host, base_path, transform, entities, parameters, limits, is_ssl=False):
    c = http_client.HTTPSConnection(host) if is_ssl else http_client.HTTPConnection(host)

    m = MaltegoTransformRequestMessage()

    for e in entities:
        m += e

    for p in parameters:
        m += p

    m += limits

    msg = MaltegoMessage(message=m).render(encoding='utf-8')
    path = re.sub(r'/+', '/', '/'.join([base_path, transform]))

    if is_debug_exec_mode():
        sys.stderr.write("Sending following message to {}{}:\n{}\n\n".format(host, path, msg))

    c.request('POST', path, msg, headers={'Content-Type': 'application/xml'})

    return c.getresponse() 
Example #2
Source File: THttpClient.py    From SOLO with GNU General Public License v3.0 5 votes vote down vote up
def open(self):
        if self.scheme == 'http':
            self.__http = http_client.HTTPConnection(self.host, self.port)
        elif self.scheme == 'https':
            self.__http = http_client.HTTPSConnection(self.host, self.port) 
Example #3
Source File: THttpClient.py    From thrift with GNU Lesser General Public License v3.0 5 votes vote down vote up
def open(self):
        if self.scheme == 'http':
            self.__http = http_client.HTTPConnection(self.host, self.port)
        elif self.scheme == 'https':
            self.__http = http_client.HTTPSConnection(self.host, self.port) 
Example #4
Source File: helper.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def setup_class(cls):
        """Create and run one HTTP server per class."""
        conf = config.copy()
        conf.update(getattr(cls, 'config', {}))

        s_class = conf.pop('server', 'wsgi')
        server_factory = cls.available_servers.get(s_class)
        if server_factory is None:
            raise RuntimeError('Unknown server in config: %s' % conf['server'])
        cls.httpserver = server_factory(**conf)

        cls.HOST, cls.PORT = cls.httpserver.bind_addr
        if cls.httpserver.ssl_adapter is None:
            ssl = ''
            cls.scheme = 'http'
        else:
            ssl = ' (ssl)'
            cls.HTTP_CONN = http_client.HTTPSConnection
            cls.scheme = 'https'

        v = sys.version.split()[0]
        log.info('Python version used to run this test script: %s' % v)
        log.info('Cheroot version: %s' % cheroot.__version__)
        log.info('HTTP server version: %s%s' % (cls.httpserver.protocol, ssl))
        log.info('PID: %s' % os.getpid())

        if hasattr(cls, 'setup_server'):
            # Clear the wsgi server so that
            # it can be updated with the new root
            cls.setup_server()
            cls.start() 
Example #5
Source File: testing.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_connection(self):
        name = '{interface}:{port}'.format(
            interface=self._interface,
            port=self._port,
        )
        conn_cls = (
            http_client.HTTPConnection
            if self.server_instance.ssl_adapter is None else
            http_client.HTTPSConnection
        )
        return conn_cls(name) 
Example #6
Source File: util.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _HTTPConnection(scheme, netloc, timeout):
    from six.moves import http_client

    if scheme == "http":
        return http_client.HTTPConnection(netloc, timeout=timeout)
    elif scheme == "https":
        return http_client.HTTPSConnection(netloc, timeout=timeout)
    else:
        raise ValueError("unsupported scheme '%s' - must be 'http' or 'https'" % scheme) 
Example #7
Source File: _thrift_api.py    From impyla with Apache License 2.0 5 votes vote down vote up
def open(self):
    if self.scheme == 'http':
      self.__http = http_client.HTTPConnection(self.host, self.port,
                                               timeout=self.__timeout)
    elif self.scheme == 'https':
      self.__http = http_client.HTTPSConnection(self.host, self.port,
                                                key_file=self.keyfile,
                                                cert_file=self.certfile,
                                                timeout=self.__timeout,
                                                context=self.context)
    if self.using_proxy():
      self.__http.set_tunnel(self.realhost, self.realport,
                             {"Proxy-Authorization": self.proxy_auth}) 
Example #8
Source File: ssl_support.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def __init__(self, host, ca_bundle, **kw):
        HTTPSConnection.__init__(self, host, **kw)
        self.ca_bundle = ca_bundle 
Example #9
Source File: helper.py    From cheroot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_class(cls):
        """Create and run one HTTP server per class."""
        conf = config.copy()
        conf.update(getattr(cls, 'config', {}))

        s_class = conf.pop('server', 'wsgi')
        server_factory = cls.available_servers.get(s_class)
        if server_factory is None:
            raise RuntimeError('Unknown server in config: %s' % conf['server'])
        cls.httpserver = server_factory(**conf)

        cls.HOST, cls.PORT = cls.httpserver.bind_addr
        if cls.httpserver.ssl_adapter is None:
            ssl = ''
            cls.scheme = 'http'
        else:
            ssl = ' (ssl)'
            cls.HTTP_CONN = http_client.HTTPSConnection
            cls.scheme = 'https'

        v = sys.version.split()[0]
        log.info('Python version used to run this test script: %s' % v)
        log.info('Cheroot version: %s' % cheroot.__version__)
        log.info('HTTP server version: %s%s' % (cls.httpserver.protocol, ssl))
        log.info('PID: %s' % os.getpid())

        if hasattr(cls, 'setup_server'):
            # Clear the wsgi server so that
            # it can be updated with the new root
            cls.setup_server()
            cls.start() 
Example #10
Source File: testing.py    From cheroot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_connection(self):
        name = '{interface}:{port}'.format(
            interface=self._interface,
            port=self._port,
        )
        conn_cls = (
            http_client.HTTPConnection
            if self.server_instance.ssl_adapter is None else
            http_client.HTTPSConnection
        )
        return conn_cls(name) 
Example #11
Source File: ssl_support.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, host, ca_bundle, **kw):
        HTTPSConnection.__init__(self, host, **kw)
        self.ca_bundle = ca_bundle 
Example #12
Source File: __init__.py    From girder_worker with Apache License 2.0 5 votes vote down vote up
def __init__(self, url, headers={}):
        self._url = url

        """
        Uses HTTP chunked transfer-encoding to stream a request body to a
        server. Unfortunately requests does not support hooking into this logic
        easily, so we use the lower-level httplib module.
        """
        self._closed = False

        parts = urllib.parse.urlparse(self._url)
        if parts.scheme == 'https':
            ssl_context = ssl.create_default_context()
            conn = httplib.HTTPSConnection(parts.netloc, context=ssl_context)
        else:
            conn = httplib.HTTPConnection(parts.netloc)

        try:
            url = parts.path
            if parts.query is not None:
                url = '%s?%s' % (url, parts.query)
            conn.putrequest('POST',
                            url, skip_accept_encoding=True)

            for header, value in headers.items():
                conn.putheader(header, value)

            conn.putheader('Transfer-Encoding', 'chunked')

            conn.endheaders()  # This actually flushes the headers to the server
        except Exception:
            sys.stderr.write('HTTP connection to "%s" failed.\n' % self._url)
            conn.close()
            raise

        self.conn = conn 
Example #13
Source File: THttpClient.py    From ajs2 with GNU General Public License v3.0 5 votes vote down vote up
def open(self):
        if self.scheme == 'http':
            self.__http = http_client.HTTPConnection(self.host, self.port)
        elif self.scheme == 'https':
            self.__http = http_client.HTTPSConnection(self.host, self.port)
            if self.using_proxy():
                self.__http.set_tunnel(self.realhost, self.realport,
                                       {"Proxy-Authorization": self.proxy_auth}) 
Example #14
Source File: client.py    From manila with Apache License 2.0 5 votes vote down vote up
def request(self, url, method='GET', body=None, headers=None):
        _headers = {'Content-Type': 'application/json'}
        _headers.update(headers or {})

        parsed_url = parse.urlparse(url)
        port = parsed_url.port
        hostname = parsed_url.hostname
        scheme = parsed_url.scheme

        if scheme == 'http':
            conn = http_client.HTTPConnection(hostname,
                                              port=port)
        elif scheme == 'https':
            conn = http_client.HTTPSConnection(hostname,
                                               port=port)
        else:
            raise OpenStackApiException("Unknown scheme: %s" % url)

        relative_url = parsed_url.path
        if parsed_url.query:
            relative_url = relative_url + "?" + parsed_url.query
        LOG.info("Doing %(method)s on %(relative_url)s",
                 {"method": method, "relative_url": relative_url})
        if body:
            LOG.info("Body: %s", body)

        conn.request(method, relative_url, body, _headers)
        response = conn.getresponse()
        return response 
Example #15
Source File: api.py    From manila with Apache License 2.0 5 votes vote down vote up
def _prepare_connection(self, isSSL, ip, port):
        if isSSL:
            if hasattr(ssl, '_create_unverified_context'):
                context = ssl._create_unverified_context()
                connection = http_client.HTTPSConnection(ip,
                                                         port=port,
                                                         context=context)
            else:
                connection = http_client.HTTPSConnection(ip,
                                                         port=port)
        else:
            connection = http_client.HTTPConnection(ip, port)
        return connection 
Example #16
Source File: THttpClient.py    From Aditmadzs2 with GNU General Public License v3.0 5 votes vote down vote up
def open(self):
        if self.scheme == 'http':
            self.__http = http_client.HTTPConnection(self.host, self.port)
        elif self.scheme == 'https':
            self.__http = http_client.HTTPSConnection(self.host, self.port)
            if self.using_proxy():
                self.__http.set_tunnel(self.realhost, self.realport,
                                       {"Proxy-Authorization": self.proxy_auth}) 
Example #17
Source File: THttpClient.py    From Protect4 with GNU General Public License v3.0 5 votes vote down vote up
def open(self):
        if self.scheme == 'http':
            self.__http = http_client.HTTPConnection(self.host, self.port)
        elif self.scheme == 'https':
            self.__http = http_client.HTTPSConnection(self.host, self.port)
            if self.using_proxy():
                self.__http.set_tunnel(self.realhost, self.realport,
                                       {"Proxy-Authorization": self.proxy_auth}) 
Example #18
Source File: transport.py    From linepy-modified with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open(self):
        if self.request == 'hyper':
            if self.http2:
                self.__http = hyper.HTTP20Connection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
            else:
                self.__http = hyper.HTTPConnection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
        elif self.request == 'httpx':
            if self.http2:
                self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2)
            else:
                self.__http = httpx.Client(base_url='%s://%s' % (self.scheme, self.host))
        elif self.request == 'requests':
            self.__http = requests.Session()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'requests-futures':
            self.__http = FuturesSession()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'httplib2':
            self.__http = httplib2.Http()
        else:
            if self.scheme == 'http':
                self.__http = http_client.HTTPConnection(self.host, self.port)
            elif self.scheme == 'https':
                self.__http = http_client.HTTPSConnection(self.host, self.port)
                if self.using_proxy():
                    self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers) 
Example #19
Source File: chunked_request.py    From lddmm-ot with MIT License 4 votes vote down vote up
def _connect(self):
        ''' Initialize an HTTP/HTTPS connection with chunked Transfer-Encoding
        to server:port with optional headers.
        '''
        server = self._server
        port = self._port
        headers = self._headers
        ssl_enabled = self._ssl_enabled
        proxy_server, proxy_port = self._get_proxy_config()

        if (proxy_server and proxy_port):
            if ssl_enabled:
                context = self._get_ssl_context()
                self._conn = http_client.HTTPSConnection(
                    proxy_server, proxy_port, context=context
                )
            else:
                self._conn = http_client.HTTPConnection(
                    proxy_server, proxy_port
                )
            self._conn.set_tunnel(server, port)
        else:
            if ssl_enabled:
                context = self._get_ssl_context()
                self._conn = http_client.HTTPSConnection(
                    server, port, context=context
                )
            else:
                self._conn = http_client.HTTPConnection(server, port)

        self._conn.putrequest('POST', self._url)
        self._conn.putheader('Transfer-Encoding', 'chunked')
        for header in headers:
            self._conn.putheader(header, headers[header])
        self._conn.endheaders()

        # Set blocking to False prevents recv
        # from blocking while waiting for a response.
        self._conn.sock.setblocking(False)
        self._bytes = six.b('')
        self._reset_retries()
        time.sleep(0.5) 
Example #20
Source File: http_transport.py    From azure-iot-sdk-python with MIT License 4 votes vote down vote up
def request(self, method, path, callback, body="", headers={}, query_params=""):
        """
        This method creates a connection to a remote host, sends a request to that host, and then waits for and reads the response from that request.

        :param str method: The request method (e.g. "POST")
        :param str path: The path for the URL
        :param Function callback: The function that gets called when this operation is complete or has failed. The callback function must accept an error and a response dictionary, where the response dictionary contains a status code, a reason, and a response string.
        :param str body: The body of the HTTP request to be sent following the headers.
        :param dict headers: A dictionary that provides extra HTTP headers to be sent with the request.
        :param str query_params: The optional query parameters to be appended at the end of the URL.
        """
        # Sends a complete request to the server
        logger.info("sending https request.")
        try:
            logger.debug("creating an https connection")
            connection = http_client.HTTPSConnection(self._hostname, context=self._ssl_context)
            logger.debug("connecting to host tcp socket")
            connection.connect()
            logger.debug("connection succeeded")
            # TODO: URL formation should be moved to pipeline_stages_iothub_http, I believe, as
            # depending on the operation this could have a different hostname, due to different
            # destinations. For now this isn't a problem yet, because no possible client can
            # support more than one HTTP operation
            # (Device can do File Upload but NOT Method Invoke, Module can do Method Inovke and NOT file upload)
            url = "https://{hostname}/{path}{query_params}".format(
                hostname=self._hostname,
                path=path,
                query_params="?" + query_params if query_params else "",
            )
            logger.debug("Sending Request to HTTP URL: {}".format(url))
            logger.debug("HTTP Headers: {}".format(headers))
            logger.debug("HTTP Body: {}".format(body))
            connection.request(method, url, body=body, headers=headers)
            response = connection.getresponse()
            status_code = response.status
            reason = response.reason
            response_string = response.read()

            logger.debug("response received")
            logger.debug("closing connection to https host")
            connection.close()
            logger.debug("connection closed")
            logger.info("https request sent, and response received.")
            response_obj = {"status_code": status_code, "reason": reason, "resp": response_string}
            callback(response=response_obj)
        except Exception as e:
            logger.error("Error in HTTP Transport: {}".format(e))
            callback(
                error=exceptions.ProtocolClientError(
                    message="Unexpected HTTPS failure during connect", cause=e
                )
            )