Beispiel #1
0
 def _get_object(self, *args, **kwargs):
     try:
         obj = self.__class__(name='get', route=self.route,
                              http_method='get', api_level=self.api_level)
         raw_text = obj.run(*args, **kwargs)
         utils.debug(raw_text)
         if raw_text is None:
             return {}
         json_text = json.loads(raw_text)
         filtered = self._filter_json_object(json_text['data'],
                                             filter_createonly=True)
         return json.dumps(filtered, indent=2)
     except Exception as e:
         utils.reraise(e)
Beispiel #2
0
 def _get_object(self, *args, **kwargs):
     try:
         obj = self.__class__(name='get',
                              route=self.route,
                              http_method='get',
                              api_level=self.api_level)
         raw_text = obj.run(*args, **kwargs)
         utils.debug(raw_text)
         if raw_text is None:
             return {}
         json_text = json.loads(raw_text)
         filtered = self._filter_json_object(json_text['data'],
                                             filter_createonly=True)
         return json.dumps(filtered, indent=2)
     except Exception as e:
         utils.reraise(e)
Beispiel #3
0
    def _format_response(self, response, hidden=False, **kwargs):
        text = None

        if response:
            try:
                response_json = json.loads(response)
            except ValueError:
                utils.debug("Server response: {}".format(str(response)))
                utils.reraise("Invalid server response")

            if response_json.get('errors'):
                error_data = response_json['errors'][0]
                error = click.ClickException(error_data['message'])
                error.code = error_data.get('code')
                raise error

            if not hidden:
                utils.debug(response_json.get('meta'))

            if hidden:
                pass
            elif settings.view in ('raw', 'json'):
                click.echo(response)
            elif settings.view == 'xml':
                click.echo(dicttoxml.dicttoxml(response_json))
            elif settings.view == 'tree':
                data = json.dumps(response_json.get('data'))
                click.echo(view.build_tree(data))
            elif settings.view == 'table':
                columns = self._table_columns or self._get_column_names()
                rows, current_page, last_page = view.calc_table(
                    response_json, columns)
                pre = "Page: {} of {}".format(current_page, last_page)
                click.echo(view.build_table(columns, rows, pre=pre))  # XXX
        elif self.http_method.upper() == 'DELETE':
            deleted_id = ''
            for param, value in kwargs.items():
                if 'Id' in param and param != 'envId':
                    deleted_id = value
                    break
            text = "Deleted {}".format(deleted_id)
        return text
Beispiel #4
0
    def pre(self, *args, **kwargs):
        """
        Before request is made.
        """
        kwargs = self._apply_arguments(**kwargs)
        self._check_arguments(**kwargs)

        import_data = kwargs.pop('import-data', {})
        #interactive = kwargs.pop('interactive', None)
        stdin = kwargs.pop('stdin', None)
        http_method = self.http_method.upper()

        if http_method not in ('PATCH', 'POST'):
            return args, kwargs

        # prompting for body and then validating it
        for param_name in (p['name'] for p in self._get_body_type_params()):
            try:
                if param_name in import_data:
                    json_object = self._filter_json_object(
                        import_data[param_name], filter_createonly=True
                    ) if http_method == 'PATCH' else import_data[param_name]
                else:
                    if http_method == 'PATCH':
                        if stdin:
                            # XXX: `_get_object` makes additional GET to load all
                            # discriminator's into `self._discriminators` map
                            self._get_object(*args, **kwargs)
                            json_object = self._read_object()
                        else:
                            json_object = self._edit_object(*args, **kwargs)
                    elif http_method == 'POST':
                        json_object = self._read_object(
                        ) if stdin else self._edit_example()

                json_object = self._filter_json_object(json_object)
                kwargs[param_name] = json_object
            except ValueError as e:
                utils.reraise(e)

        return args, kwargs
Beispiel #5
0
    def pre(self, *args, **kwargs):
        """
        Before request is made.
        """
        kwargs = self._apply_arguments(**kwargs)
        self._check_arguments(**kwargs)

        import_data = kwargs.pop('import-data', {})
        #interactive = kwargs.pop('interactive', None)
        stdin = kwargs.pop('stdin', None)
        http_method = self.http_method.upper()

        if http_method not in ('PATCH', 'POST'):
            return args, kwargs

        # prompting for body and then validating it
        for param_name in (p['name'] for p in self._get_body_type_params()):
            try:
                if param_name in import_data:
                    json_object = self._filter_json_object(
                        import_data[param_name],
                        filter_createonly=True
                    ) if http_method == 'PATCH' else import_data[param_name]
                else:
                    if http_method == 'PATCH':
                        if stdin:
                            # XXX: `_get_object` makes additional GET to load all
                            # discriminator's into `self._discriminators` map
                            self._get_object(*args, **kwargs)
                            json_object = self._read_object()
                        else:
                            json_object = self._edit_object(*args, **kwargs)
                    elif http_method == 'POST':
                        json_object = self._read_object() if stdin else self._edit_example()

                json_object = self._filter_json_object(json_object)
                kwargs[param_name] = json_object
            except ValueError as e:
                utils.reraise(e)

        return args, kwargs
Beispiel #6
0
    def _format_response(self, response, hidden=False, **kwargs):
        text = None

        if response:
            try:
                response_json = json.loads(response)
            except ValueError:
                utils.debug("Server response: {}".format(str(response)))
                utils.reraise("Invalid server response")

            errors = response_json.get('errors')

            if errors:
                errmsg = self._format_errmsg(errors)
                error = MultipleClickException(errmsg)
                error.code = 1
                raise error

            if not hidden:
                utils.debug(response_json.get('meta'))

            if self.strip_metadata and self.http_method.upper() == 'GET' and \
                    settings.view in ('raw', 'json', 'xml') and 'data' in response_json:  # SCALRCORE-10392
                response_json = response_json['data']
                response = json.dumps(response_json)

            if hidden:
                pass
            elif settings.view in ('raw', 'json'):
                click.echo(response)
            elif settings.view == 'xml':
                click.echo(dicttoxml.dicttoxml(response_json))
            elif settings.view == 'tree':
                data = json.dumps(response_json.get('data'))
                click.echo(view.build_tree(data))
            elif settings.view == 'table':
                columns = self._table_columns or self._get_column_names()
                if self._returns_iterable():
                    rows, current_page, last_page = view.calc_vertical_table(
                        response_json, columns)
                    pre = "Page: {} of {}".format(current_page, last_page)
                    click.echo(
                        view.build_vertical_table(columns, rows,
                                                  pre=pre))  # XXX
                else:
                    click.echo(
                        view.build_horizontal_table(
                            view.calc_horizontal_table(response_json,
                                                       columns)))

        elif self.http_method.upper() == 'DELETE':
            deleted_id = kwargs.get(self.delete_target, '') or ''
            if not deleted_id:
                for param, value in kwargs.items():
                    if 'Id' in param and param not in ('envId', 'accountId'):
                        deleted_id = value
                        break
            if not deleted_id:
                for param, value in kwargs.items():
                    if 'Name' in param:
                        deleted_id = value
                        break
            text = "Deleted {}".format(deleted_id)
        return text
Beispiel #7
0
    def _format_response(self, response, hidden=False, **kwargs):
        text = None

        if response:
            try:
                response_json = json.loads(response)
            except ValueError:
                utils.debug("Server response: {}".format(str(response)))
                utils.reraise("Invalid server response")

            errors = response_json.get('errors')
            warnings = response_json.get('warnings')  # type: list[dict]

            if warnings:
                utils.warning(*warnings)

            if errors:
                errmsg = self._format_errmsg(errors)
                error = MultipleClickException(errmsg)
                error.code = 1
                raise error

            if not hidden:
                utils.debug(response_json.get('meta'))

            if self.strip_metadata and self.http_method.upper() == 'GET' and \
                    settings.view in ('raw', 'json', 'xml') and 'data' in response_json:  # SCALRCORE-10392
                response_json = response_json['data']
                response = json.dumps(response_json)

            if hidden:
                pass
            elif settings.view in ('raw', 'json'):
                click.echo(response)
            elif settings.view == 'xml':
                click.echo(dicttoxml.dicttoxml(response_json))
            elif settings.view == 'tree':
                data = json.dumps(response_json.get('data'))
                click.echo(view.build_tree(data))
            elif settings.view == 'table':
                columns = self._table_columns or self._get_column_names()
                if self._returns_iterable():
                    rows, current_page, last_page = view.calc_vertical_table(response_json,
                                                                    columns)
                    pre = "Page: {} of {}".format(current_page, last_page)
                    click.echo(view.build_vertical_table(columns, rows, pre=pre))  # XXX
                else:
                    click.echo(view.build_horizontal_table(
                        view.calc_horizontal_table(response_json, columns)))

        elif self.http_method.upper() == 'DELETE':
            deleted_id = kwargs.get(self.delete_target, '') or ''
            if not deleted_id:
                for param, value in kwargs.items():
                    if 'Id' in param and param not in ('envId', 'accountId'):
                        deleted_id = value
                        break
            if not deleted_id:
                for param, value in kwargs.items():
                    if 'Name' in param:
                        deleted_id = value
                        break
            text = "Deleted {}".format(deleted_id)
        return text