Example #1
0
    def demand_json(self, method, endpoint, data=None):
        """Call demand method and only return json data."""
        try:
            self.demand(method, endpoint, data)
            json_data = json.loads(self.api_result.text)

        except json.decoder.JSONDecodeError as error:
            msg = '%s %s "%s"' % ('Invalid json data received.', str(error),
                                  self.api_result.text)
            self.logger.error('ApiRequesterError # ' + msg)
            raise RbkcliException.ApiRequesterError(msg)

        return json.dumps(json_data, indent=2, sort_keys=True)
Example #2
0
    def demand(self, method, endpoint, data=None, params=None):
        """Perform API request with provided data."""
        self._create_url(endpoint)
        self._create_auth_header()

        try:
            self.api_result = requests.request(method,
                                               self.url,
                                               params=params,
                                               data=data,
                                               headers=self.auth_prpt.header,
                                               verify=self.VERIFICATION)

            self._validate_token_auth(method, endpoint, data={}, params={})

        except requests.exceptions.ConnectionError as error:
            self.logger.error('ApiRequesterError # ' + str(error))
            raise RbkcliException.ApiRequesterError(str(error))

        except requests.exceptions.InvalidURL as error:
            self.logger.print_error('ApiRequesterError # ' + str(error))
            raise RbkcliException.ApiRequesterError(str(error))

        return self.api_result
Example #3
0
    def _create_username_header(self, msg):
        """Create the username authentication header for API request."""
        self.logger.warning('ApiRequester # ' + msg)
        try:
            credentials = ('%s:%s' % (self.auth.username, self.auth.password))
            # Python 2 compatibility
            try:
                base64bytes = base64.encodebytes(credentials.encode('utf-8'))
            except AttributeError:
                base64bytes = base64.b64encode(credentials.encode('utf-8'))

            auth = 'Basic ' + base64bytes.decode('utf-8').replace('\n', '')
            self.auth_prpt.type_ = 'username'
        except KeyError as bad_key:
            msg = ('%s%s%s.' %
                   (self.auth_prpt.primary_exception,
                    ' Expected authorization key not found ', str(bad_key)))
            msg = msg.strip(' ')
            self.logger.error('%s%s' % ('ApiRequesterError # ', msg))
            raise RbkcliException.ApiRequesterError(msg)
        return auth
Example #4
0
    def _validate_token_auth(self, method, endpoint, data, params):
        """Validate last token authentication."""
        error_msg = 'The supplied authentication is invalid'
        error_msg2 = '"message":"Incorrect username/password"'
        if (self.api_result.text == error_msg
                and self.auth_prpt.type_ == 'token'):
            error_msg = 'The supplied TOKEN authentication is invalid.'
            self.auth_prpt.primary_exception = error_msg
            error_msg = '%s %s' % (error_msg, 'Attempting to use secondary'
                                   ' auth type (username/password).')
            self.logger.warning('ApiRequester # ' + error_msg)

            self.demand(method, endpoint, data, params)
        elif (error_msg2 in self.api_result.text
              and self.auth_prpt.type_ == 'username'):
            error_msg = 'The supplied authentication is invalid'
            self.logger.error('ApiRequester # ' + error_msg)
            error_msg = error_msg + '.\n'
            raise RbkcliException.ApiRequesterError(error_msg)
        else:
            # Log successful actions
            msg = '%s [%s:%s]' % ('ApiRequester # Successfully requested API',
                                  method, self.url)
            self.logger.debug(msg)