def format_response(response, fmt='json', filter='.', changed=False): if response is None: return # HTTP 204 if isinstance(response, six.text_type): return response if 'results' in response.__dict__: results = getattr(response, 'results') else: results = [response] for result in results: if 'related' in result.json: result.json.pop('related') formatted = FORMATTERS[fmt](response.json, filter) if changed: formatted = colored(formatted, 'green') return formatted
def parse_action(self, page, from_sphinx=False): """Perform an HTTP OPTIONS request This method performs an HTTP OPTIONS request to build a list of valid actions, and (if provided) runs the code for the action specified on the CLI :param page: a awxkit.api.pages.TentativePage object representing the top-level resource in question (e.g., /api/v2/jobs) :param from_sphinx: a flag specified by our sphinx plugin, which allows us to walk API OPTIONS using this function _without_ triggering a SystemExit (argparse's behavior if required arguments are missing) """ subparsers = self.subparsers[self.resource].add_subparsers( dest='action', metavar='action') subparsers.required = True # parse the action from OPTIONS parser = ResourceOptionsParser(self.v2, page, self.resource, subparsers) if parser.deprecated: description = 'This resource has been deprecated and will be removed in a future release.' if not from_sphinx: description = colored(description, 'yellow') self.subparsers[self.resource].description = description if from_sphinx: # Our Sphinx plugin runs `parse_action` for *every* available # resource + action in the API so that it can generate usage # strings for automatic doc generation. # # Because of this behavior, we want to silently ignore the # `SystemExit` argparse will raise when you're missing required # positional arguments (which some actions have). try: self.parser.parse_known_args(self.argv)[0] except SystemExit: pass else: self.parser.parse_known_args()[0] # parse any action arguments if self.resource != 'settings': for method in ('list', 'modify', 'create'): if method in parser.parser.choices: parser.build_query_arguments( method, 'GET' if method == 'list' else 'POST') if from_sphinx: parsed, extra = self.parser.parse_known_args(self.argv) else: parsed, extra = self.parser.parse_known_args() if extra and self.verbose: # If extraneous arguments were provided, warn the user cprint('{}: unrecognized arguments: {}'.format( self.parser.prog, ' '.join(extra)), 'yellow', file=self.stdout) # build a dictionary of all of the _valid_ flags specified on the # command line so we can pass them on to the underlying awxkit call # we ignore special global flags like `--help` and `--conf.xyz`, and # the positional resource argument (i.e., "jobs") # everything else is a flag used as a query argument for the HTTP # request we'll make (e.g., --username="******", --verbosity=3) parsed = parsed.__dict__ parsed = dict((k, v) for k, v in parsed.items() if (v is not None and k not in ( 'help', 'resource') and not k.startswith('conf.'))) # if `id` is one of the arguments, it's a detail view if 'id' in parsed: page.endpoint += '{}/'.format(str(parsed.pop('id'))) # determine the awxkit method to call action = self.original_action = parsed.pop('action') page, action = handle_custom_actions(self.resource, action, page) self.method = { 'list': 'get', 'modify': 'patch', }.get(action, action) if self.method == 'patch' and not parsed: # If we're doing an HTTP PATCH with an empty payload, # just print the help message (it's a no-op anyways) parser.parser.choices['modify'].print_help() return if self.help: # If --help is specified on a subarg parser, bail out # and print its help text parser.parser.choices[self.original_action].print_help() return if self.original_action == 'create': return page.post(parsed) return getattr(page, self.method)(**parsed)