Example #1
0
 def _get_token(self):
     """
     Retrieve an authorization token if not supplied.
     """
     
     # If a token is already supplied
     if self.api_token:
         return True
     
     # Authentication URL
     auth_url       = '%s/%s' % (self.api_url, PATH.GET_TOKEN)
     
     # Get an API token
     self.token_rsp = parse_response(requests.get(auth_url, headers=self._get_token_headers()))
 
     # Load the response body
     self.token_rsp['body'] = json.loads(self.token_rsp['body'])
 
     # If token request looks OK
     if self.token_rsp['code'] == 200:
         
         # Load the authorization token
         self.api_token = self.token_rsp['body']['token']
     
         # Token retrieval OK
         return True
     
     # Failed to retrieve a token
     else:
         return False
Example #2
0
    def _return(self, response):
        """
        Parse and return the response.
        """
        
        # Parse the response
        parsed = parse_response(response)
        
        # Parse the body
        try:
            parsed['body'] = json.loads(parsed['body'])
        except:
            pass
        
        # If there was an error during the request
        if parsed['code'] != 200:
            error_response(parsed['body']['message'], response=parsed, cli=self.cli)

        # Return a successfull response
        return parsed
Example #3
0
 def request(self, path, action, data=None):
     """
     Make an internal API request.
     """
     
     # Make sure an API user and token are defined
     if not self.api_user or not self.api_token:
         return self.log.error('Failed to make API request, API user and/or token not set')
     
     # Define the full utility
     util = '%s/%s' % (path, action)
     
     # If data is supplied, make sure it is valid
     if data and not isinstance(data, dict):
         return self.log.error('Failed to make API request, request data must be in dictionary format')
     
     # Make sure the endpoint is valid
     if not endpoint in self.endpoints:
         return self.log.error('Failed to make API request, endpoint not found: %s/%s' % (path, action))
     
     # Log the request details
     self.log.info('Submitting API request: endpoint=%s, api_user=%s, data=%s' % (endpoint, self.api_user, ('None' if not data else json.dumps(data))))
     
     # Attempt to construct a new request object
     try:
         
         # Define the request defaults
         defaults = {
             'REQUEST_METHOD': self.endpoints[endpoint]['method'],
             'SERVER_NAME':    self.conf.server.host,
             'PATH_INFO':      '/%s' % path,
             'REQUEST_URI':    '/cloudscape-api/%s' % path,
             'SCRIPT_NAME':    '/cloudscape-api',
             'SERVER_PORT':    '10550',
             'CONTENT_TYPE':   'application/json'
         }
         
         # Create a new instance of the request factory
         rf = RequestFactory(**defaults)
         
         # Construct the request object
         request_obj = rf.request()
         
         # Define the request body
         body = {
             'api_user':  self.api_user,
             'api_token': self.api_token,
             'api_group': self.api_group,
             'action':    action
         }
         
         # If any request data
         if data:
             body['_data'] = data
         
         # Set the request body
         request_obj._body = json.dumps(body)
         
     # Critical error when constructing request object
     except Exception as e:
         self.log.exception('Failed to construct request object: %s' % str(e))
     
     # Dispatch the request and get the response
     response = parse_response(request.dispatch(request_obj))
     
     # Load the response body
     def load_body(body):
         try:
             return json.loads(body)
         except:
             return body
     
     # Return the response
     return {
         'code': response['code'],
         'body': load_body(response['body'])
     }