def request(method, path, params=None, payload=None, parser=None, headers=None): """Create a generic handler for passing to specific request methods. :param method: the request method to execute :param path: path after server and port (i.e. /api/v1/credentials) :param params: uri encoding params (i.e. ?param1=hello¶m2=world) :param payload: dictionary of payload to be posted :param parser: parser for printing usage on failure :param headers: headers to include :returns: reponse object :raises: AssertionError error if method is not supported """ # grab the cli command for the log if the parser is provided log_command = None if parser is not None: log_command = parser.prog req_headers = {} token = read_client_token() # create the url by adding the path to the configured server location url = get_server_location() + path if headers: req_headers.update(headers) if token: req_headers['Authorization'] = 'Token {}'.format(token) try: if method == POST: result = handle_general_errors(post(url, payload, req_headers)) elif method == GET: result = handle_general_errors(get(url, params, req_headers)) elif method == PATCH: result = handle_general_errors(patch(url, payload, req_headers)) elif method == DELETE: result = handle_general_errors(delete(url, req_headers)) elif method == PUT: result = handle_general_errors(put(url, payload, req_headers)) else: log.error('Unsupported request method %s', method) parser.print_help() sys.exit(1) try: log_request_info(method, log_command, url, result.json(), result.status_code) except ValueError: log_request_info(method, log_command, url, result.text, result.status_code) return result except requests.exceptions.SSLError as ssl_error: print(_(SSL_ERROR_MSG)) log.error(ssl_error) if parser is not None: parser.print_help() sys.exit(1) except requests.exceptions.ConnectionError as conn_err: print(_(CONNECTION_ERROR_MSG)) log.error(conn_err) if parser is not None: parser.print_help() sys.exit(1)
def main(self): """Execute of subcommand operation. Method determine whether to display usage or pass input to find the best command match. If no match is found the usage is displayed """ self.args = self.parser.parse_args() setup_logging(self.args.verbosity) if self.args.subcommand != server.SUBCOMMAND or \ (self.args.subcommand == server.SUBCOMMAND and self.args.action != server.CONFIG): # Before attempting to run command, check server location server_location = get_server_location() if server_location is None or server_location == '': log.error(_(messages.SERVER_CONFIG_REQUIRED)) log.error('$ qpc server config --host HOST --port PORT') sys.exit(1) if (self.args.subcommand != server.SUBCOMMAND and not read_client_token()): log.error(_(messages.SERVER_LOGIN_REQUIRED)) log.error('$ qpc server login') sys.exit(1) if self.args.subcommand in self.subcommands: subcommand = self.subcommands[self.args.subcommand] if self.args.action in subcommand: action = subcommand[self.args.action] action.main(self.args) else: self.parser.print_help() else: self.parser.print_help()
def main(self): """Execute of subcommand operation. Method determine whether to display usage or pass input to find the best command match. If no match is found the usage is displayed """ self.args = self.parser.parse_args() setup_logging(self.args.verbosity) is_server_cmd = self.args.subcommand == server.SUBCOMMAND is_server_logout = is_server_cmd and self.args.action == server.LOGOUT is_server_config = is_server_cmd and self.args.action == server.CONFIG if not is_server_config: # Before attempting to run command, check server location server_location = get_server_location() if server_location is None or server_location == '': log.error(_(messages.SERVER_CONFIG_REQUIRED % PKG_NAME)) sys.exit(1) if read_require_auth(): if ((not is_server_cmd or is_server_logout) and not read_client_token()): log.error(_(messages.SERVER_LOGIN_REQUIRED % PKG_NAME)) sys.exit(1) if self.args.subcommand in self.subcommands: subcommand = self.subcommands[self.args.subcommand] if self.args.action in subcommand: action = subcommand[self.args.action] action.main(self.args) else: self.parser.print_help() else: self.parser.print_help()
def test_read_client_token(self): """Testing the read client token function.""" check_value = False if not os.path.exists(utils.QPC_CLIENT_TOKEN): check_value = True expected_token = '100' token_json = {'token': expected_token} utils.write_client_token(token_json) token = utils.read_client_token() self.assertTrue(isinstance(token, str)) if check_value: self.assertEqual(token, expected_token)
def request(method, path, params=None, payload=None, parser=None, headers=None): """Create a generic handler for passing to specific request methods. :param method: the request method to execute :param path: path after server and port (i.e. /api/v1/credentials) :param params: uri encoding params (i.e. ?param1=hello¶m2=world) :param payload: dictionary of payload to be posted :param parser: parser for printing usage on failure :param headers: headers to include :returns: reponse object :raises: AssertionError error if method is not supported """ req_headers = {} token = read_client_token() if headers: req_headers.update(headers) if token: req_headers['Authorization'] = 'Token {}'.format(token) try: if method == POST: return post(path, payload, req_headers) elif method == GET: return get(path, params, req_headers) elif method == PATCH: return patch(path, payload, req_headers) elif method == DELETE: return delete(path, req_headers) elif method == PUT: return put(path, payload, req_headers) else: log.error('Unsupported request method %s', method) parser.print_help() sys.exit(1) except requests.exceptions.SSLError as ssl_error: print(_(SSL_ERROR_MSG)) log.error(ssl_error) if parser is not None: parser.print_help() sys.exit(1) except requests.exceptions.ConnectionError as conn_err: print(_(CONNECTION_ERROR_MSG)) log.error(conn_err) if parser is not None: parser.print_help() sys.exit(1)
def request(method, path, params=None, payload=None, parser=None, headers=None, min_server_version=QPC_MIN_SERVER_VERSION): """Create a generic handler for passing to specific request methods. :param method: the request method to execute :param path: path after server and port (i.e. /api/v1/credentials) :param params: uri encoding params (i.e. ?param1=hello¶m2=world) :param payload: dictionary of payload to be posted :param parser: parser for printing usage on failure :param headers: headers to include :param min_server_version: min qpc server version allowed :returns: reponse object :raises: AssertionError error if method is not supported """ # grab the cli command for the log if the parser is provided log_command = None if parser is not None: log_command = parser.prog req_headers = {} token = read_client_token() # create the url by adding the path to the configured server location url = get_server_location() + path if headers: req_headers.update(headers) if token: req_headers['Authorization'] = 'Token {}'.format(token) try: if method == POST: result = handle_general_errors(post(url, payload, req_headers), min_server_version) elif method == GET: result = handle_general_errors(get(url, params, req_headers), min_server_version) elif method == PATCH: result = handle_general_errors(patch(url, payload, req_headers), min_server_version) elif method == DELETE: result = handle_general_errors(delete(url, req_headers), min_server_version) elif method == PUT: result = handle_general_errors(put(url, payload, req_headers), min_server_version) else: log.error('Unsupported request method %s', method) parser.print_help() sys.exit(1) try: log_request_info(method, log_command, url, result.json(), result.status_code) except ValueError: log_request_info(method, log_command, url, result.text, result.status_code) return result except (requests.exceptions.ConnectionError, requests.exceptions.SSLError): config = read_server_config() if config is not None: protocol = 'https' host = config.get(CONFIG_HOST_KEY) port = config.get(CONFIG_PORT_KEY) if config.get(CONFIG_USE_HTTP): protocol = 'http' log.error(_(CONNECTION_ERROR_MSG % (protocol, host, port))) log.error(_(messages.SERVER_CONFIG_REQUIRED % PKG_NAME)) else: log.error(_(messages.SERVER_CONFIG_REQUIRED % PKG_NAME)) sys.exit(1)