Пример #1
0
    def __init_connection(self, url=None):
        """Function for initiating connection with remote server

        :param url: The URL of the remote system
        :type url: str

        """
        self.__destroy_connection()

        url = url if url else self.__url
        if url.scheme.upper() == "HTTPS":
            if sys.version_info < (2, 7, 9):
                self._conn = http_client.HTTPSConnection(url.netloc)
            else:
                self._conn = http_client.HTTPSConnection(url.netloc, \
                                    context=ssl._create_unverified_context())
        elif url.scheme.upper() == "HTTP":
            self._conn = http_client.HTTPConnection(url.netloc)
        else:
            pass
Пример #2
0
def create_connection(parsed_url):
    """Helper function to create connection with httplib

    :param parsed_url: parsed url of the remote location
    """
    if parsed_url.scheme == 'https':
        conn = httplib.HTTPSConnection(parsed_url.netloc)
    else:
        conn = httplib.HTTPConnection(parsed_url.netloc)

    return conn
Пример #3
0
    def _call(self, action, resource, data, headers, binary=False):
        if resource.startswith('http'):
            uri = resource
        else:
            uri = self.base_uri + resource
        if binary:
            body = data
        else:
            body = jsonutils.dumps(data)

        debug_data = 'binary' if binary else body
        debug_data = debug_data if debug_data else 'EMPTY'
        if not headers:
            headers = {'Authorization': 'Basic %s' % self.auth}
        else:
            headers['Authorization'] = 'Basic %s' % self.auth
        conn = None
        if self.ssl:
            conn = http_client.HTTPSConnection(self.server,
                                               self.port,
                                               timeout=self.timeout)
            if conn is None:
                LOG.error(
                    _LE('vdirectRESTClient: Could not establish HTTPS '
                        'connection'))
                return 0, None, None, None
        else:
            conn = http_client.HTTPConnection(self.server,
                                              self.port,
                                              timeout=self.timeout)
            if conn is None:
                LOG.error(
                    _LE('vdirectRESTClient: Could not establish HTTP '
                        'connection'))
                return 0, None, None, None

        try:
            conn.request(action, uri, body, headers)
            response = conn.getresponse()
            respstr = response.read()
            respdata = respstr
            try:
                respdata = jsonutils.loads(respstr)
            except ValueError:
                # response was not JSON, ignore the exception
                pass
            ret = (response.status, response.reason, respstr, respdata)
        except Exception as e:
            log_dict = {'action': action, 'e': e}
            LOG.error(_LE('vdirectRESTClient: %(action)s failure, %(e)r'),
                      log_dict)
            ret = -1, None, None, None
        conn.close()
        return ret
Пример #4
0
    def __init__(self, uri_or_host, speedThrift=False, port=None, path=None):
        """THttpClient supports two different types constructor parameters.

        THttpClient(host, port, path) - deprecated
        THttpClient(uri)

        Only the second supports https.
        """
        if port is not None:
            warnings.warn(
                "Please use the THttpClient('http://host:port/path') syntax",
                DeprecationWarning,
                stacklevel=2)
            self.host = uri_or_host
            self.port = port
            assert path
            self.path = path
            self.scheme = 'http'
        else:
            parsed = urllib.parse.urlparse(uri_or_host)
            self.scheme = parsed.scheme
            assert self.scheme in ('http', 'https')
            if self.scheme == 'http':
                self.port = parsed.port or http_client.HTTP_PORT
            elif self.scheme == 'https':
                self.port = parsed.port or http_client.HTTPS_PORT
            self.host = parsed.hostname
            self.path = parsed.path
            if parsed.query:
                self.path += '?%s' % parsed.query
        try:
            proxy = urllib.request.getproxies()[self.scheme]
        except KeyError:
            proxy = None
        else:
            if urllib.request.proxy_bypass(self.host):
                proxy = None
        if proxy:
            parsed = urllib.parse.urlparse(proxy)
            self.realhost = self.host
            self.realport = self.port
            self.host = parsed.hostname
            self.port = parsed.port
            self.proxy_auth = self.basic_proxy_auth_header(parsed)
        else:
            self.realhost = self.realport = self.proxy_auth = None
        self.__wbuf = BytesIO()
        self.__http = http_client.HTTPSConnection(self.host, self.port)  #None
        self.__http_response = None
        self.__timeout = None
        self.__custom_headers = None
        self.__timeStart = time.time()
        self.__speedThrift = speedThrift
Пример #5
0
 def _performAction(self, actionName, params=None):
     if not params:
         params = {}
     params['Action'] = actionName
     #https://email.us-east-1.amazonaws.com/
     conn = http_client.HTTPSConnection('email.us-east-1.amazonaws.com')
     params = urlencode(params)
     conn.request('POST', '/', params, self._getHeaders())
     response = conn.getresponse()
     responseResult = response.read()
     conn.close()
     return self._responseParser.parse(actionName, response.status, response.reason, responseResult)
Пример #6
0
    def prepare_upload_key(self,
                           key,
                           public_id,
                           private_id,
                           serial=None,
                           user_agent='python-yubikey-manager/' + __version__):
        modhex_public_id = modhex_encode(public_id)
        data = {
            'aes_key': b2a_hex(key).decode('utf-8'),
            'serial': serial or 0,
            'public_id': modhex_public_id,
            'private_id': b2a_hex(private_id).decode('utf-8'),
        }

        httpconn = http_client.HTTPSConnection(UPLOAD_HOST, timeout=1)  # nosec

        try:
            httpconn.request('POST',
                             UPLOAD_PATH,
                             body=json.dumps(data,
                                             indent=False,
                                             sort_keys=True).encode('utf-8'),
                             headers={
                                 'Content-Type': 'application/json',
                                 'User-Agent': user_agent,
                             })
        except Exception as e:
            logger.error('Failed to connect to %s', UPLOAD_HOST, exc_info=e)
            raise PrepareUploadFailed(None, None,
                                      [PrepareUploadError.CONNECTION_FAILED])

        resp = httpconn.getresponse()
        if resp.status == 200:
            url = json.loads(resp.read().decode('utf-8'))['finish_url']
            return url
        else:
            resp_body = resp.read()
            logger.debug('Upload failed with status %d: %s', resp.status,
                         resp_body)
            if resp.status == 404:
                raise PrepareUploadFailed(resp.status, resp_body,
                                          [PrepareUploadError.NOT_FOUND])
            elif resp.status == 503:
                raise PrepareUploadFailed(
                    resp.status, resp_body,
                    [PrepareUploadError.SERVICE_UNAVAILABLE])
            else:
                try:
                    errors = json.loads(
                        resp_body.decode('utf-8')).get('errors')
                except Exception:
                    errors = []
                raise PrepareUploadFailed(resp.status, resp_body, errors)
    def test_http_mock_failure(self):
        mock_body = '{"error": "no results matching query", "status": 413}'

        self.mock_response.read.return_value = mock_body
        self.mock_response.status = 413

        conn = http_client.HTTPSConnection('whatever', None)
        conn.request('GET', '/blah', '{}', {})
        rsp = conn.getresponse()

        self.assertEqual(mock_body, rsp.read())
        self.assertEqual(413, rsp.status)
Пример #8
0
 def _fetch_response_xml(self, request_xml):
     # Need to fill in HTTP request here
     conn = http_client.HTTPSConnection(self._host, 443, timeout=30)
     headers = {"Content-type": "application/xml",
                "Accept": ""}
     conn.request("POST", self._path, request_xml.encode('utf8'), headers)
     response = conn.getresponse()
     response_xml = response.read()
     if response.status != http_client.OK:
         raise GatewayError("Unable to communicate with payment gateway (code: %s, response: %s)" % (response.status, response_xml))
     conn.close()
     return response_xml
Пример #9
0
def __GetElementTree(protocol, server, port, path, sslContext, httpProxyHost=None, httpProxyPort=None):
   """
   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 httpProxyHost:
      kwargs = {"context": sslContext} if sslContext else {}
      conn = http_client.HTTPSConnection(httpProxyHost, port=httpProxyPort, **kwargs)
      conn.set_tunnel(server, port)
   elif protocol == "https":
      kwargs = {"context": sslContext} if sslContext else {}
      # IPv6 requires None as the port
      if port:
         server = server + ":" + str(port)
      conn = http_client.HTTPSConnection(server, None, **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
Пример #10
0
 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})
Пример #11
0
 def get_connection_secure(self, verbose):
     """
     Notes
     -----------------
     Add certificate to connection
     """
     # Prepare the certificate
     context = ssl.create_default_context()
     if self.__certificate:
         context.load_cert_chain(self.__certificate)
     return httplib.HTTPSConnection(self._ConnectionHandler__connHost,
                                    self._ConnectionHandler__connPortSsl,
                                    context=context)
Пример #12
0
def rpc_pypi(method, *args):
    """Call an XML-RPC method on the Pypi server."""
    conn = http_client.HTTPSConnection(PYPI_HOSTNAME)
    headers = {'Content-Type': 'text/xml'}
    payload = xmlrpc_client.dumps(args, method)

    conn.request("POST", "/pypi", payload, headers)
    response = conn.getresponse()
    if response.status == 200:
        result = xmlrpc_client.loads(response.read())[0][0]
        return result
    else:
        raise RuntimeError("Unable to download the list of top "
                           "packages from Pypi.")
Пример #13
0
    def __init__(self, uri_or_host, port=None, path=None, customThrift=True):
        """THttpClient supports two different types constructor parameters.

        THttpClient(host, port, path) - deprecated
        THttpClient(uri)

        Only the second supports https.
        """
        if port is not None:
            warnings.warn(
                "Please use the THttpClient('http://host:port/path') syntax",
                DeprecationWarning,
                stacklevel=2
            )
            self.host = uri_or_host
            self.port = port
            assert path
            self.path = path
            self.scheme = 'http'
        else:
            parsed = urllib.parse.urlparse(uri_or_host)
            self.scheme = parsed.scheme
            
            assert self.scheme in ('http', 'https')
            if self.scheme == 'http':
                self.port = parsed.port or http_client.HTTP_PORT
            elif self.scheme == 'https':
                self.port = parsed.port or http_client.HTTPS_PORT
            self.host = parsed.hostname
            self.path = parsed.path
            if parsed.query:
                self.path += '?%s' % parsed.query
        proxy = None
        self.realhost = self.realport = self.proxy_auth = None
        self.__wbuf = BytesIO()
        if customThrift:
            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)
        else:
            self.__http = None
               
        self.__http_response = None
        self.__timeout = None
        self.__custom_headers = None
        self.__time = time.time()
        self.__custom_thrift = customThrift
        self.__loop = 0
Пример #14
0
    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:
                self._conn = http_client.HTTPSConnection(
                    proxy_server, proxy_port)
            else:
                self._conn = http_client.HTTPConnection(
                    proxy_server, proxy_port)
            self._conn.set_tunnel(server, port)
        else:
            if ssl_enabled:
                self._conn = http_client.HTTPSConnection(server, port)
            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)
Пример #15
0
 def get_connection(self, ishttps=False, cookie=None, verbose=False):
     """
     Notes
     -----------------
     If using certificates get secure not if using cookies
     """
     if self.__certificate is not None:
         if verbose:
             print("------>Cert")
         return self.get_connection_secure(verbose)
     else:
         if verbose:
             print("------>Cookie")
         return httplib.HTTPSConnection(self._ConnectionHandler__connHost,
                                        self._ConnectionHandler__connPort)
Пример #16
0
    def http_connection(session):
        conn = None

        xs_url = urllib.parse.urlparse(session.url)
        LOG.debug("Creating http(s) connection to %s" % session.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 request(self,
             endpoint,
             method=None,
             body=None,
             headers=None):
     # Strip 'https://'
     https_con = http_client.HTTPSConnection(
         endpoint[8:].split('/')[0])
     https_con.request(method,
                       endpoint,
                       body=body,
                       headers=headers)
     response = https_con.getresponse()
     # Return status like an httplib2 response.
     return ({'status': response.status}, )
Пример #18
0
def send_message(message):
    message = message.encode('utf-8')

    headers = {
        b'Content-Type': b'text/xml',
        b'SOAPAction': b'urn:ec.europa.eu:taxud:tic:services:VatRateWebService'
    }

    tries = 0
    response = None
    while response is None or (tries < 5 and response.status >= 500
                               and response.status <= 599):
        if tries > 0:
            if response is not None:
                # Cope with badly behaved web service returning 500 for non-
                # server errors
                body = response.read()
                if body.startswith(b'<soap:'):
                    root = etree.fromstring(body)
                    fault = root.find('.//' + SOAP_NS + 'Fault')

                    faultcode = fault.find('./{*}faultcode').text
                    faultstring = fault.find('./{*}faultstring').text
                    faultactor = fault.find('./{*}faultactor')
                    if faultactor is not None:
                        faultactor = faultactor.text
                    detail = fault.find('./{*}detail')
                    if detail is not None:
                        detail = detail.text

                    m = _error_re.match(faultstring)
                    if m:
                        raise VRWSErrorException(int(m.group(1)), m.group(2))

                    raise VRWSSOAPException(faultcode, faultstring, faultactor,
                                            detail)

            time.sleep(tries)
        tries += 1
        conn = http_client.HTTPSConnection(VRWS_HOST)
        conn.request(str('POST'), VRWS_PATH, message, headers)
        response = conn.getresponse()

    if response.status != 200:
        raise VRWSHTTPException(response.status, response.reason,
                                response.getheaders(), response.read())

    return response
Пример #19
0
    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()
Пример #20
0
    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")
            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
                )
            )
Пример #21
0
 def list(self):
     if isinstance(self.hotfixes, dict):
         return self.hotfixes
     self.hotfixes = {}
     conn = http_client.HTTPSConnection(self.url.netloc)
     try:
         conn.request('GET', self.url.path)
         response = conn.getresponse()
     except Exception as error:
         logging.warning("Could not get hotfix list: %s", error)
         return {}
     hotfixes = yaml.load(response)
     for name in hotfixes:
         if not HotFixManager.isHotfixValid(hotfixes[name]):
             continue
         self.hotfixes[name] = self.processHotfix(name, hotfixes[name])
     return self.hotfixes
Пример #22
0
    def make_connection(self, host):
        if self._connection and host == self._connection[0]:
            return self._connection[1]

        chost, self._extra_headers, x509 = self.get_host_info(host)

        if self.secure:
            try:
                self._connection = host, httplib.HTTPSConnection(
                    chost, None, **(x509 or {}))
            except AttributeError:
                raise NotImplementedError(
                    'In use version of httplib doesn\'t support HTTPS')
        else:
            self._connection = host, httplib.HTTPConnection(chost)

        return self._connection[1]
Пример #23
0
    def _request(self, method, url):
        con = http_client.HTTPSConnection(self.host, timeout=self.timeout)
        with closing(con):
            log.debug("%s host=%s url=%s", method, self.host, url)
            con.request(method, url)
            res = con.getresponse()
            body = res.read()
            if res.status != http_client.OK:
                raise Error(
                    "Request failed host={} url={} reason={} body={!r}".format(
                        host, url, res.reason, body))

        log.debug("OK headers=%s", res.getheaders())

        if body.startswith(_MAGIC_PREFIX):
            body = body[len(_MAGIC_PREFIX):]

        return json.loads(body)
Пример #24
0
def do_http(method, url, body=b""):
    if isinstance(body, bytes):
        body = BytesIO(body)
    elif isinstance(body, six.text_type):
        raise TypeError("do_http body must be a bytestring, not unicode")
    else:
        # We must give a Content-Length header to twisted.web, otherwise it
        # seems to get a zero-length file. I suspect that "chunked-encoding"
        # may fix this.
        assert body.tell
        assert body.seek
        assert body.read
    scheme, host, port, path = parse_url(url)
    if scheme == "http":
        c = http_client.HTTPConnection(host, port)
    elif scheme == "https":
        c = http_client.HTTPSConnection(host, port)
    else:
        raise ValueError("unknown scheme '%s', need http or https" % scheme)
    c.putrequest(method, path)
    c.putheader("Hostname", host)
    c.putheader("User-Agent", allmydata.__full_version__ + " (tahoe-client)")
    c.putheader("Accept", "text/plain, application/octet-stream")
    c.putheader("Connection", "close")

    old = body.tell()
    body.seek(0, os.SEEK_END)
    length = body.tell()
    body.seek(old)
    c.putheader("Content-Length", str(length))

    try:
        c.endheaders()
    except socket_error as err:
        return BadResponse(url, err)

    while True:
        data = body.read(8192)
        if not data:
            break
        c.send(data)

    return c.getresponse()
Пример #25
0
    def _connect(self):
        # Host and port for the HTTP(S) connection to the API server.
        if self.ca_certs == 'HTTP':
            api_port = 80
        else:
            api_port = 443
        if self.port is not None:
            api_port = self.port

        # Host and port for outer HTTP(S) connection if proxied.
        if self.proxy_type is None:
            host = self.host
            port = api_port
        elif self.proxy_type == 'CONNECT':
            host = self.proxy_host
            port = self.proxy_port
        else:
            raise NotImplementedError('proxy_type=%s' % (self.proxy_type, ))

        # Create outer HTTP(S) connection.
        if self.ca_certs == 'HTTP':
            conn = http_client.HTTPConnection(host, port)
        elif self.ca_certs == 'DISABLE':
            conn = http_client.HTTPSConnection(host, port)
        else:
            conn = CertValidatingHTTPSConnection(host,
                                                 port,
                                                 ca_certs=self.ca_certs)

        # Override default socket timeout if requested.
        conn.timeout = self.timeout

        # Configure CONNECT proxy tunnel, if any.
        if self.proxy_type == 'CONNECT':
            if hasattr(conn, 'set_tunnel'):  # 2.7+
                conn.set_tunnel(self.host, api_port, self.proxy_headers)
            elif hasattr(conn, '_set_tunnel'):  # 2.6.3+
                # pylint: disable=E1103
                conn._set_tunnel(self.host, api_port, self.proxy_headers)
                # pylint: enable=E1103

        return conn
Пример #26
0
 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)
Пример #27
0
    def request(self, method, path, body=None, headers=None):

        if not headers:
            headers = {}

        headers.update(self.default_headers)

        if not self.port:
            self.port = 443 if self.secure else 80

        if self.secure:
            ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
            self.http_conn = http_client.HTTPSConnection(self.host,
                                                         self.port,
                                                         timeout=self.timeout,
                                                         context=ctx)
        else:
            self.http_conn = http_client.HTTPConnection(self.host,
                                                        self.port,
                                                        timeout=self.timeout)

        if self.authenticator:
            self.authenticator.add_auth(headers)

        self.http_conn.request(method, self.root + path, body, headers=headers)
        response = self.http_conn.getresponse()
        body = response.read()
        try:
            data = json.loads(body)
        except ValueError:
            data = body

        if response.status in [401, 403]:
            raise errors.AuthenticationError()
        elif response.status == 500:
            raise errors.InternalServerError()
        elif response.status == 400:
            raise errors.BadRequestError(body)
        elif response.status == 404:
            raise errors.NotFoundError()

        return (response, data)
Пример #28
0
def fb_refresh_access_token(refresh_token, auth_settings):
    connection = http_client.HTTPSConnection('graph.facebook.com', 443)
    headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
    body = 'fb_exchange_token={0}&client_id={1}&client_secret={2}&redirect_uri={3}'.format(refresh_token, auth_settings['client_id'],
                                                                                           auth_settings['client_secret'], auth_settings['redirect_uri'])
    connection.request('POST', '/v2.3/oauth/access_token', body, headers)
    response = connection.getresponse()

    if response.status == 200:
        response_data = json.loads(response.read())

        fb_refresh_token_data = {
            'access_token': response_data['access_token'],
            'expires_in': response_data['expires_in'],
            'refresh_token': response_data['refresh_token']
        }

        return fb_refresh_token_data
    else:
        raise Exception(response.read())
Пример #29
0
    def unmock_putrequest(conn,
                          method,
                          url,
                          skip_host=False,
                          skip_accept_encoding=False):
        """putrequest mock; called initially after the HTTPConnection object has been created. Contains information
        about the endpoint and method.

        :param conn
        :type conn HTTPConnection
        :param method
        :type method string
        :param url
        :type url string
        :param skip_host
        :type skip_host bool
        :param skip_accept_encoding
        :type skip_accept_encoding bool
        """
        if unmock_options._is_host_whitelisted(
                conn.host):  # Host is whitelisted, redirect to original call.
            original_putrequest(conn, method, url, skip_host,
                                skip_accept_encoding)

        elif not hasattr(conn, "unmock"):
            # Otherwise, we create our own HTTPSConnection to redirect the call to our service when needed.
            # We add the "unmock" attribute to this object and store information for later use.
            uri = parse_url(url)
            req = http_client.HTTPSConnection(unmock_options._unmock_host,
                                              unmock_options._unmock_port,
                                              timeout=conn.timeout)
            setattr(req, "unmock_data",
                    UnmockData(path=uri.path, query=uri.query, method=method))
            if token is not None:  # Add token to official headers
                # Added as a 1-tuple as the actual call to `putheader` (later on) unpacks it
                req.unmock_data.headers["Authorization"] = (
                    "Bearer {token}".format(token=token), )
            ua_key, ua_value = unmock_user_agent()
            req.unmock_data.headers[ua_key] = (ua_value, )
            setattr(conn, "unmock", req)
Пример #30
0
 def __init__(self, url, user_credentials, ca_file=None):
     parsedurl = urlparse.urlparse(url)
     self._url = parsedurl.geturl()
     self._netloc = parsedurl.netloc
     self._ca_file = ca_file
     if parsedurl.scheme == 'https':
         if self._ca_file:
             self._connection = HTTPSConnectionWithCaVerification(
                 self._netloc, ca_file=self._ca_file.name)
         else:
             self._connection = http_client.HTTPSConnection(self._netloc)
             LOG.warning(
                 _LW("Will not verify the server certificate of the API service"
                     " because the CA certificate is not available."))
     else:
         self._connection = http_client.HTTPConnection(self._netloc)
     self._id = 0
     self._fail_fast = True
     self._credentials = BasicAuthCredentials(user_credentials[0],
                                              user_credentials[1])
     self._require_cert_verify = self._ca_file is not None
     self._disabled_cert_verification = False