我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用six.moves.http_client.HTTPSConnection()。
def _connect_request(self, vdi_ref): # request connection to xapi url service for VDI export try: # create task for VDI export label = 'VDI_EXPORT_for_' + self.instance['name'] desc = 'Exporting VDI for instance: %s' % self.instance['name'] self.task_ref = self.session.task.create(label, desc) LOG.debug("task_ref is %s" % self.task_ref) # connect to XS xs_url = urlparse.urlparse(self.host_url) if xs_url.scheme == 'http': conn = httplib.HTTPConnection(xs_url.netloc) LOG.debug("using http") elif xs_url.scheme == 'https': conn = httplib.HTTPSConnection(xs_url.netloc) LOG.debug("using https") vdi_export_path = utils.get_vdi_export_path( self.session, self.task_ref, vdi_ref) conn.request('GET', vdi_export_path) conn_resp = conn.getresponse() except Exception: LOG.debug('request connect for vdi export failed') raise return conn_resp
def connect(self, method, content_length, cookie): try: if self._scheme == 'http': conn = httplib.HTTPConnection(self._server) elif self._scheme == 'https': # TODO(browne): This needs to be changed to use python requests conn = httplib.HTTPSConnection(self._server) # nosec else: excep_msg = _("Invalid scheme: %s.") % self._scheme LOG.error(excep_msg) raise ValueError(excep_msg) conn.putrequest(method, '/folder/%s?%s' % (self.path, self._query)) conn.putheader('User-Agent', constants.USER_AGENT) conn.putheader('Content-Length', content_length) conn.putheader('Cookie', cookie) conn.endheaders() LOG.debug("Created HTTP connection to transfer the file with " "URL = %s.", str(self)) return conn except (httplib.InvalidURL, httplib.CannotSendRequest, httplib.CannotSendHeader) as excep: excep_msg = _("Error occurred while creating HTTP connection " "to write to file with URL = %s.") % str(self) LOG.exception(excep_msg) raise exceptions.VimConnectionException(excep_msg, excep)
def OpenPathWithStub(path, stub): """ Open the specified path using HTTP, using the host/port/protocol associated with the specified stub. If the stub has a session cookie, it is included with the HTTP request. Returns the response as a file-like object. """ from six.moves import http_client if not hasattr(stub, 'scheme'): raise vmodl.fault.NotSupported() elif stub.scheme == http_client.HTTPConnection: protocol = 'http' elif stub.scheme == http_client.HTTPSConnection: protocol = 'https' else: raise vmodl.fault.NotSupported() hostPort = stub.host url = '%s://%s%s' % (protocol, hostPort, path) headers = {} if stub.cookie: headers["Cookie"] = stub.cookie return requests.get(url, headers=headers, verify=False)
def __call__(self, path, key_file=None, cert_file=None, **kwargs): # Only pass in the named arguments that HTTPConnection constructor # understands tmpKwargs = {} for key in http_client.HTTPConnection.__init__.__code__.co_varnames: if key in kwargs and key != 'self': tmpKwargs[key] = kwargs[key] tunnel = http_client.HTTPConnection(path, **tmpKwargs) tunnel.request('CONNECT', self.proxyPath) resp = tunnel.getresponse() if resp.status != 200: raise http_client.HTTPException("{0} {1}".format(resp.status, resp.reason)) retval = http_client.HTTPSConnection(path) retval.sock = _SocketWrapper(tunnel.sock, keyfile=key_file, certfile=cert_file) return retval
def _create_connection(scheme, netloc): if scheme == 'https': conn = httplib.HTTPSConnection(netloc) else: conn = httplib.HTTPConnection(netloc) conn.connect() return conn
def http_connection(self): conn = None xs_url = urllib.parse.urlparse(self.url) LOG.debug("Creating http(s) connection to %s", self.url) if xs_url.scheme == 'http': conn = http_client.HTTPConnection(xs_url.netloc) elif xs_url.scheme == 'https': conn = http_client.HTTPSConnection(xs_url.netloc) conn.connect() try: yield conn finally: conn.close()
def __init__(self, host, ca_bundle, **kw): HTTPSConnection.__init__(self, host, **kw) self.ca_bundle = ca_bundle
def __GetElementTree(protocol, server, port, path, sslContext): """ Private method that returns a root from ElementTree for a remote XML document. @param protocol: What protocol to use for the connection (e.g. https or http). @type protocol: string @param server: Which server to connect to. @type server: string @param port: Port @type port: int @param path: Path @type path: string @param sslContext: SSL Context describing the various SSL options. It is only supported in Python 2.7.9 or higher. @type sslContext: SSL.Context """ if protocol == "https": kwargs = {"context": sslContext} if sslContext else {} conn = http_client.HTTPSConnection(server, port=port, **kwargs) elif protocol == "http": conn = http_client.HTTPConnection(server, port=port) else: raise Exception("Protocol " + protocol + " not supported.") conn.request("GET", path) response = conn.getresponse() if response.status == 200: try: tree = ElementTree.fromstring(response.read()) return tree except ExpatError: pass return None ## Private method that returns an ElementTree describing the API versions ## supported by the specified server. The result will be vimServiceVersions.xml ## if it exists, otherwise vimService.wsdl if it exists, otherwise None.
def _VerifyThumbprint(thumbprint, connection): '''If there is a thumbprint, connect to the server and verify that the SSL certificate matches the given thumbprint. An exception is thrown if there is a mismatch.''' if thumbprint and isinstance(connection, http_client.HTTPSConnection): if not connection.sock: connection.connect() derCert = connection.sock.getpeercert(True) sha1 = hashlib.sha1() sha1.update(derCert) sha1Digest = sha1.hexdigest().lower() if sha1Digest != thumbprint: raise ThumbprintMismatchException(thumbprint, sha1Digest) # Function used to wrap sockets with SSL
def _VerifyThumbprint(thumbprint, connection): if thumbprint and isinstance(connection, http_client.HTTPSConnection): raise Exception( "Thumbprint verification not supported on python < 2.6")
def _SocketWrapper(rawSocket, keyfile, certfile, *args, **kwargs): wrappedSocket = socket.ssl(rawSocket, keyfile, certfile) return http_client.FakeSocket(rawSocket, wrappedSocket) ## Internal version of https connection # # Support ssl.wrap_socket params which are missing from httplib # HTTPSConnection (e.g. ca_certs) # Note: Only works if the ssl params are passing in as kwargs
def connect(self): if len(self._sslArgs) == 0: # No override http_client.HTTPSConnection.connect(self) return # Big hack. We have to copy and paste the httplib connect fn for # each python version in order to handle extra ssl paramters. Yuk! if hasattr(self, "source_address"): # Python 2.7 sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) if self._tunnel_host: self.sock = sock self._tunnel() self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, **self._sslArgs) elif hasattr(self, "timeout"): # Python 2.6 sock = socket.create_connection((self.host, self.port), self.timeout) self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, **self._sslArgs) else: # Unknown python version. Do nothing http_client.HTTPSConnection.connect(self) return # TODO: Additional verification of peer cert if needed # cert_reqs = self._sslArgs.get("cert_reqs", ssl.CERT_NONE) # ca_certs = self._sslArgs.get("ca_certs", None) # if cert_reqs != ssl.CERT_NONE and ca_certs: # if hasattr(self.sock, "getpeercert"): # # TODO: verify peer cert # dercert = self.sock.getpeercert(False) # # pemcert = ssl.DER_cert_to_PEM_cert(dercert) ## Stand-in for the HTTPSConnection class that will connect to a proxy and ## issue a CONNECT command to start an SSL tunnel.
def __init__(self, proxyPath): self.proxyPath = proxyPath # Connects to a proxy server and initiates a tunnel to the destination # specified by proxyPath. If successful, a new HTTPSConnection is returned. # # @param path The destination URL path. # @param key_file The SSL key file to use when wrapping the socket. # @param cert_file The SSL certificate file to use when wrapping the socket. # @param kwargs In case caller passed in extra parameters not handled by # SSLTunnelConnection
def connect(self): httplib.HTTPSConnection.connect(self) timeout = getattr(self, "_timeout", 0) if timeout: self.sock.settimeout(timeout)
def connect(self): try: self.__connect = http_client.HTTPSConnection("slack.com") return self.__connect except Exception as e: raise ConnectionError("Failed connection.")
def _vhd_stream_to_vdi(self, vhd_file_parser, vdi_ref, file_size): headers = {'Content-Type': 'application/octet-stream', 'Content-Length': '%s' % file_size} if self.host_url.scheme == 'http': conn = httplib.HTTPConnection(self.host_url.netloc) elif self.host_url.scheme == 'https': conn = httplib.HTTPSConnection(self.host_url.netloc) vdi_import_path = utils.get_vdi_import_path( self.session, self.task_ref, vdi_ref) try: conn.connect() except Exception: LOG.error('Failed connecting to host: %s', self.host_url.netloc) raise exception.HostConnectionFailure( host_netloc=self.host_url.netloc) try: conn.request('PUT', vdi_import_path, headers=headers) # Send the data already processed by vhd file parser firstly; # then send the remaining data from the stream. conn.send(vhd_file_parser.cached_buff) remain_size = file_size - len(vhd_file_parser.cached_buff) file_obj = vhd_file_parser.src_file while remain_size >= CHUNK_SIZE: chunk = file_obj.read(CHUNK_SIZE) remain_size -= CHUNK_SIZE conn.send(chunk) if remain_size != 0: chunk = file_obj.read(remain_size) conn.send(chunk) except Exception: LOG.error('Failed importing VDI from VHD stream - vdi_ref:%s', vdi_ref) raise exception.VdiImportFailure(vdi_ref=vdi_ref) finally: resp = conn.getresponse() LOG.debug("Connection response status/reason is " "%(status)s:%(reason)s", {'status': resp.status, 'reason': resp.reason}) conn.close()
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)