예제 #1
0
 def invalidRequestException(self, message=None):
     """
     Raises an invalid request error with a default translated string
     :param message: Custom message to add to exception. If it is None, "Invalid Request" is used
     """
     message = _('Invalid Request') if message is None else message
     raise RequestError('{} {}: {}'.format(message, self.__class__, self._args))
예제 #2
0
 def getGui(self, parent, forType):  # pylint: disable=no-self-use
     '''
     Gets the gui that is needed in order to "edit/add" new items on this detail
     If not overriden, means that the detail has no edit/new Gui
     :param parent: Parent object
     :param forType: Type of object needing gui
     :return: a "gui" (list of gui fields)
     '''
     raise RequestError('Gui not provided for this type of object')
예제 #3
0
    def readFieldsFromParams(self, fldList):  # pylint: disable=no-self-use
        """
        Reads the indicated fields from the parameters received, and if
        :param fldList: List of required fields
        :return: A dictionary containing all required fields
        """
        args = {}
        try:
            for key in fldList:
                args[key] = self._params[key]
                del self._params[key]
        except KeyError as e:
            raise RequestError('needed parameter not found in data {0}'.format(six.text_type(e)))

        return args
예제 #4
0
    def delete(self) -> str:
        """
        Processes a DELETE request
        """
        if len(self._args) != 1:
            raise RequestError('Delete need one and only one argument')

        self.ensureAccess(self.model(), permissions.PERMISSION_ALL, root=True)  # Must have write permissions to delete

        try:
            self.model.objects.get(token=self._args[0]).delete()
        except self.model.DoesNotExist:
            raise NotFound('Element do not exists')

        return OK
예제 #5
0
파일: model.py 프로젝트: j4ackwolf/openuds
    def doFilter(self, data):
        # Right now, filtering only supports a single filter, in a future
        # we may improve it
        if self.fltr is None:
            return data

        # Filtering a non iterable (list or tuple)
        if not isinstance(data, (list, tuple, types.GeneratorType)):
            return data

        logger.debug('data: {}, fltr: {}'.format(data, self.fltr))
        try:
            fld, pattern = self.fltr.split('=')
            s, e = '', ''
            if pattern[0] == '^':
                pattern = pattern[1:]
                s = '^'
            if pattern[-1] == '$':
                pattern = pattern[:-1]
                e = '$'

            r = re.compile(s + fnmatch.translate(pattern) + e,
                           re.RegexFlag.IGNORECASE)

            def fltr_function(item):
                try:
                    if fld not in item or r.match(item[fld]) is None:
                        return False
                except Exception:
                    return False
                return True

            res = list(filter(fltr_function, data))

            logger.debug('After filtering: {}'.format(res))
            return res
        except:
            logger.exception('Exception:')
            logger.info('Filtering expression {} is invalid!'.format(
                self.fltr))
            raise RequestError('Filtering expression {} is invalid'.format(
                self.fltr))

        return data
예제 #6
0
    def delete(self):
        """
        Processes a DELETE request
        """
        logger.debug('method DELETE for {0}, {1}'.format(self.__class__.__name__, self._args))
        if len(self._args) > 1:
            return self.processDetail()

        if len(self._args) != 1:
            raise RequestError('Delete need one and only one argument')

        self.ensureAccess(self.model(), permissions.PERMISSION_ALL, root=True)  # Must have write permissions to delete

        try:
            item = self.model.objects.get(uuid=self._args[0].lower())
            self.checkDelete(item)
            self.deleteItem(item)
        except self.model.DoesNotExist:
            raise NotFound('Element do not exists')

        return OK
예제 #7
0
    def put(self):
        '''
        Processes a PUT request
        '''
        logger.debug('method PUT for {0}, {1}'.format(self.__class__.__name__,
                                                      self._args))
        self._params['_request'] = self._request

        deleteOnError = False

        if len(self._args) > 1:  # Detail?
            return self.processDetail()

        self.ensureAccess(
            self.model(), permissions.PERMISSION_ALL,
            root=True)  # Must have write permissions to create, modify, etc..

        try:
            # Extract fields
            args = self.readFieldsFromParams(self.save_fields)
            logger.debug('Args: {}'.format(args))
            self.beforeSave(args)
            # If tags is in save fields, treat it "specially"
            if 'tags' in self.save_fields:
                tags = args['tags']
                del args['tags']
            else:
                tags = None

            deleteOnError = False
            if len(self._args) == 0:  # create new
                item = self.model.objects.create(**args)
                deleteOnError = True
            else:  # Must have 1 arg
                # We have to take care with this case, update will efectively update records on db
                item = self.model.objects.get(uuid=self._args[0].lower())
                for v in self.remove_fields:
                    if v in args:
                        del args[v]
                item.__dict__.update(args)  # Update fields from args

            # Now if tags, update them
            if tags is not None:
                logger.debug('Updating tags: {}'.format(tags))
                item.tags = [
                    Tag.objects.get_or_create(tag=val)[0] for val in tags
                ]

        except self.model.DoesNotExist:
            raise NotFound('Item not found')
        except IntegrityError:  # Duplicate key probably
            raise RequestError('Element already exists (duplicate key error)')
        except SaveException as e:
            raise RequestError(unicode(e))
        except (RequestError, ResponseError):
            raise
        except Exception:
            logger.exception('Exception on put')
            raise RequestError('incorrect invocation to PUT')

        if not deleteOnError:
            self.checkSave(
                item
            )  # Will raise an exception if item can't be saved (only for modify operations..)

        # Store associated object if needed
        try:
            data_type = self._params.get('data_type', self._params.get('type'))
            if data_type is not None:
                item.data_type = data_type
                item.data = item.getInstance(self._params).serialize()

            item.save()

            res = self.item_as_dict(item)
            self.fillIntanceFields(item, res)
        except:
            if deleteOnError:
                item.delete()
            raise

        self.afterSave(item)

        return res
예제 #8
0
 def invalidMethodException(self):
     '''
     Raises a NotFound exception with translated "Method not found" string to current locale
     '''
     raise RequestError(
         _('Method not found in {}: {}'.format(self.__class__, self._args)))