示例#1
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.warning(
                    u'Permission denied to %s: "%s"' %
                    (self._get_action_name(past=True).lower(), datum_display))
                continue
            try:
                self.action(request, datum_id)
                # Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info(u'%s: "%s"' %
                         (self._get_action_name(past=True), datum_display))
            except Exception as ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                action_failure.append(datum_display)
                action_description = (self._get_action_name(past=True).lower(),
                                      datum_display)
                LOG.warning('Action %(action)s Failed for %(reason)s', {
                    'action': action_description,
                    'reason': ex
                })

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You are not allowed to %(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_not_allowed).lower(),
                "objs": functions.lazy_join(", ", action_not_allowed)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_failure).lower(),
                "objs": functions.lazy_join(", ", action_failure)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_success, past=True),
                "objs": functions.lazy_join(", ", action_success)
            }
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#2
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or _("N/A")
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.info('Permission denied to %s: "%s"' %
                         (self._conjugate(past=True).lower(), datum_display))
                continue
            try:
                self.action(request, datum_id)
                #Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info('%s: "%s"' %
                         (self._conjugate(past=True), datum_display))
            except Exception as ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                if getattr(ex, "_safe_message", None):
                    ignore = False
                else:
                    ignore = True
                    action_failure.append(datum_display)
                exceptions.handle(request, ignore=ignore)

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You do not have permission to %(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_not_allowed).lower(),
                "objs": functions.lazy_join(", ", action_not_allowed)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_failure).lower(),
                "objs": functions.lazy_join(", ", action_failure)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_success, True),
                "objs": functions.lazy_join(", ", action_success)
            }
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#3
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []

        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or _("N/A")
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_id)
                LOG.info('Permission denied to %s: "%s"' %
                         (self._get_action_name(past=True).lower(),
                          datum_id))
                continue
            try:
                self.action(request, datum_id)
                self.update(request, datum)
                action_success.append(datum_id)
                self.success_ids.append(datum_id)
                LOG.info('%s: "%s"' %
                         (self._get_action_name(past=True), datum_id))
            except Exception as ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                if getattr(ex, "_safe_message", None):
                    ignore = False
                else:
                    ignore = True
                    action_failure.append(datum_id)
                exceptions.handle(request, ignore=ignore)

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You are not allowed to %(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_not_allowed).lower(),
                      "objs": functions.lazy_join(", ", action_not_allowed)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {"action": self._get_action_name(action_failure).lower(),
                      "objs": functions.lazy_join(", ", action_failure)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_success, past=True),
                      "objs": functions.lazy_join(", ", action_success)}
            success_message_level(request, msg % params)
            for host in obj_ids:
                if host not in HOSTS_ALL:
                    HOSTS_ALL.append(host)
        return shortcuts.redirect(self.get_success_url(request))
示例#4
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.warning(u'Permission denied to %(name)s: "%(dis)s"', {
                    'name': self._get_action_name(past=True).lower(),
                    'dis': datum_display
                })
                continue
            try:
                self.action(request, datum_id)
                # Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info(u'%s: "%s"' %
                         (self._get_action_name(past=True), datum_display))
            except Exception as ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                action_failure.append(datum_display)
                action_description = (
                    self._get_action_name(past=True).lower(), datum_display)
                LOG.warning(
                    'Action %(action)s Failed for %(reason)s', {
                        'action': action_description, 'reason': ex})

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You are not allowed to %(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_not_allowed).lower(),
                      "objs": functions.lazy_join(", ", action_not_allowed)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {"action": self._get_action_name(action_failure).lower(),
                      "objs": functions.lazy_join(", ", action_failure)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_success, past=True),
                      "objs": functions.lazy_join(", ", action_success)}
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#5
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or _("N/A")
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.info('Permission denied to %s: "%s"' %
                         (self._conjugate(past=True).lower(), datum_display))
                continue
            try:
                self.action(request, datum_id)
                #Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info('%s: "%s"' %
                         (self._conjugate(past=True), datum_display))
            except:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                exceptions.handle(request, ignore=True)
                action_failure.append(datum_display)

        #Begin with success message class, downgrade to info if problems
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You do not have permission to %(action)s: %(objs)s')
            params = {"action": self._conjugate(action_not_allowed).lower(),
                      "objs": functions.lazy_join(", ", action_not_allowed)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {"action": self._conjugate(action_failure).lower(),
                      "objs": functions.lazy_join(", ", action_failure)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {"action": self._conjugate(action_success, True),
                      "objs": functions.lazy_join(", ", action_success)}
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#6
0
    def handle(self, table, request, obj_ids):
        if not table.data:
            msg = _("Cannot grow cluster.  No instances specified.")
            messages.info(request, msg)
            return shortcuts.redirect(request.build_absolute_uri())

        datum_display_objs = []
        for instance in table.data:
            msg = _("[flavor=%(flavor)s, volume=%(volume)s, name=%(name)s, "
                    "type=%(type)s, related_to=%(related_to)s]")
            params = {"flavor": instance.flavor_id, "volume": instance.volume,
                      "name": instance.name, "type": instance.type,
                      "related_to": instance.related_to}
            datum_display_objs.append(msg % params)
        display_str = functions.lazy_join(", ", datum_display_objs)

        cluster_id = table.kwargs['cluster_id']
        try:
            api.trove.cluster_grow(request, cluster_id, table.data)
            LOG.info('%s: "%s"' % (_("Grow Cluster"), display_str))
            msg = _('Scheduled growing of cluster.')
            messages.success(request, msg)
        except Exception as ex:
            LOG.error('Action %s Failed for %s' %
                      (_("grow cluster"), display_str), ex)
            msg = _('Unable to grow cluster: %s')
            messages.error(request, msg % ex.message)
        finally:
            cluster_manager.delete(cluster_id)

        return shortcuts.redirect(urlresolvers.reverse(
            "horizon:project:database_clusters:index"))
示例#7
0
    def handle(self, table, request, obj_ids):
        datum_display_objs = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            datum_display_objs.append(datum_display)
        display_str = functions.lazy_join(", ", datum_display_objs)

        try:
            cluster_id = table.kwargs['cluster_id']
            data = [{'id': instance_id} for instance_id in obj_ids]
            api.trove.cluster_shrink(request, cluster_id, data)
            LOG.info('%s: "%s"' %
                     (self._get_action_name(past=True),
                      display_str))
            msg = _('Removed instances from cluster.')
            messages.info(request, msg)
        except Exception as ex:
            LOG.error('Action %s Failed for %s' %
                      (self._get_action_name(past=True).lower(),
                       display_str), ex)
            msg = _('Unable to remove instances from cluster: %s')
            messages.error(request, msg % ex.message)

        return shortcuts.redirect(self.get_success_url(request))
示例#8
0
    def handle(self, table, request, obj_ids):
        datum_display_objs = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            datum_display_objs.append(datum_display)
        display_str = functions.lazy_join(", ", datum_display_objs)

        try:
            cluster_id = table.kwargs['cluster_id']
            data = [{'id': instance_id} for instance_id in obj_ids]
            api.trove.cluster_shrink(request, cluster_id, data)
            LOG.info('%s: "%s"' %
                     (self._get_action_name(past=True), display_str))
            msg = _('Removed instances from cluster.')
            messages.info(request, msg)
        except Exception as ex:
            LOG.error(
                'Action %(action)s failed with %(ex)s for %(data)s' % {
                    'action': self._get_action_name(past=True).lower(),
                    'ex': ex.message,
                    'data': display_str
                })
            msg = _('Unable to remove instances from cluster: %s')
            messages.error(request, msg % ex.message)

        return shortcuts.redirect(self.get_success_url(request))
示例#9
0
    def handle(self, table, request, obj_ids):
        if not table.data:
            msg = _("Cannot grow cluster.  No instances specified.")
            messages.info(request, msg)
            return shortcuts.redirect(request.build_absolute_uri())

        datum_display_objs = []
        for instance in table.data:
            msg = _("[flavor=%(flavor)s, volume=%(volume)s, name=%(name)s, "
                    "type=%(type)s, related_to=%(related_to)s, "
                    "nics=%(nics)s]")
            params = {"flavor": instance.flavor_id, "volume": instance.volume,
                      "name": instance.name, "type": instance.type,
                      "related_to": instance.related_to, "nics": instance.nics}
            datum_display_objs.append(msg % params)
        display_str = functions.lazy_join(", ", datum_display_objs)

        cluster_id = table.kwargs['cluster_id']
        try:
            api.trove.cluster_grow(request, cluster_id, table.data)
            LOG.info('%s: "%s"' % (_("Grow Cluster"), display_str))
            msg = _('Scheduled growing of cluster.')
            messages.success(request, msg)
        except Exception as ex:
            LOG.error('Action grow cluster failed with %(ex)s for %(data)s' %
                      {'ex': six.text_type(ex),
                       'data': display_str})
            msg = _('Unable to grow cluster: %s')
            messages.error(request, msg % six.text_type(ex))
        finally:
            cluster_manager.delete(cluster_id)

        return shortcuts.redirect(urls.reverse(
            "horizon:project:database_clusters:index"))
示例#10
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.warning('Permission denied to %s: "%s"' % (self._get_action_name(past=True).lower(), datum_display))
                continue
            try:
                self.action(request, datum_id)
                # Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info('%s: "%s"' % (self._get_action_name(past=True), datum_display))
            except Exception as ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                action_failure.append(datum_display)
                action_description = (self._get_action_name(past=True).lower(), datum_display)
                LOG.error("Action %(action)s Failed for %(reason)s", {"action": action_description, "reason": ex})

        if action_not_allowed:
            msg = _("You are not allowed to %(action)s: %(objs)s")
            params = {
                "action": self._get_action_name(action_not_allowed).lower(),
                "objs": functions.lazy_join(", ", action_not_allowed),
            }
            messages.error(request, msg % params)
        if action_failure:
            msg = _("Unable to %(action)s: %(objs)s")
            params = {
                "action": self._get_action_name(action_failure).lower(),
                "objs": functions.lazy_join(", ", action_failure),
            }
            messages.error(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#11
0
    def handle(self, table, request, obj_ids):
        datum_display_objs = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            datum_display_objs.append(datum_display)
        display_str = functions.lazy_join(", ", datum_display_objs)

        try:
            cluster_id = table.kwargs["cluster_id"]
            data = [{"id": instance_id} for instance_id in obj_ids]
            api.trove.cluster_shrink(request, cluster_id, data)
            LOG.info('%s: "%s"' % (self._get_action_name(past=True), display_str))
            msg = _("Removed instances from cluster.")
            messages.info(request, msg)
        except Exception as ex:
            LOG.error(
                "Action %(action)s failed with %(ex)s for %(data)s"
                % {"action": self._get_action_name(past=True).lower(), "ex": ex.message, "data": display_str}
            )
            msg = _("Unable to remove instances from cluster: %s")
            messages.error(request, msg % ex.message)

        return shortcuts.redirect(self.get_success_url(request))
示例#12
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.warning(
                    u'Permission denied to %(name)s: "%(dis)s"', {
                        'name': self._get_action_name(past=True).lower(),
                        'dis': datum_display
                    })
                continue
            try:
                self.action(request, datum_id)
                # Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info(
                    u'%(action)s: "%(datum_display)s"', {
                        'action': self._get_action_name(past=True),
                        'datum_display': datum_display
                    })
            except Exception as ex:
                handled_exc = isinstance(ex, exceptions.HandledException)
                if handled_exc:
                    # In case of HandledException, an error message should be
                    # handled in exceptions.handle() or other logic,
                    # so we don't need to handle the error message here.
                    # NOTE(amotoki): To raise HandledException from the logic,
                    # pass escalate=True and do not pass redirect argument
                    # to exceptions.handle().
                    # If an exception is handled, the original exception object
                    # is stored in ex.wrapped[1].
                    ex = ex.wrapped[1]
                else:
                    # Handle the exception but silence it since we'll display
                    # an aggregate error message later. Otherwise we'd get
                    # multiple error messages displayed to the user.
                    action_failure.append(datum_display)
                action_description = (self._get_action_name(past=True).lower(),
                                      datum_display)
                LOG.warning('Action %(action)s Failed for %(reason)s', {
                    'action': action_description,
                    'reason': ex
                })

        success_message_level = getattr(messages, self.default_message_level)
        if action_not_allowed:
            msg = _('You are not allowed to %(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_not_allowed).lower(),
                "objs": functions.lazy_join(", ", action_not_allowed)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_failure).lower(),
                "objs": functions.lazy_join(", ", action_failure)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {
                "action": self._get_action_name(action_success, past=True),
                "objs": functions.lazy_join(", ", action_success)
            }
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#13
0
class BatchAction(Action):
    """ A table action which takes batch action on one or more
        objects. This action should not require user input on a
        per-object basis.

    .. attribute:: name

       An internal name for this action.

    .. attribute:: action_present

       String or tuple/list. The display forms of the name.
       Should be a transitive verb, capitalized and translated. ("Delete",
       "Rotate", etc.) If tuple or list - then setting
       self.current_present_action = n will set the current active item
       from the list(action_present[n])

    .. attribute:: action_past

       String or tuple/list. The past tense of action_present. ("Deleted",
       "Rotated", etc.) If tuple or list - then
       setting self.current_past_action = n will set the current active item
       from the list(action_past[n])

    .. attribute:: data_type_singular

       A display name for the type of data that receives the
       action. ("Keypair", "Floating IP", etc.)

    .. attribute:: data_type_plural

       Optional plural word for the type of data being acted
       on. Defaults to appending 's'. Relying on the default is bad
       for translations and should not be done.

    .. attribute:: success_url

       Optional location to redirect after completion of the delete
       action. Defaults to the current page.
    """
    success_url = None

    def __init__(self):
        self.current_present_action = 0
        self.current_past_action = 0
        self.data_type_plural = getattr(self, 'data_type_plural',
                                        self.data_type_singular + 's')
        self.verbose_name = getattr(self, "verbose_name", self._conjugate())
        self.verbose_name_plural = getattr(self, "verbose_name_plural",
                                           self._conjugate('plural'))
        # Keep record of successfully handled objects
        self.success_ids = []
        super(BatchAction, self).__init__()

    def _allowed(self, request, datum=None):
        # Override the default internal action method to prevent batch
        # actions from appearing on tables with no data.
        if not self.table.data and not datum:
            return False
        return super(BatchAction, self)._allowed(request, datum)

    def _conjugate(self, items=None, past=False):
        """
        Builds combinations like 'Delete Object' and 'Deleted
        Objects' based on the number of items and `past` flag.
        """
        action_type = "past" if past else "present"
        action_attr = getattr(self, "action_%s" % action_type)
        if isinstance(action_attr, (basestring, Promise)):
            action = action_attr
        else:
            toggle_selection = getattr(self, "current_%s_action" % action_type)
            action = action_attr[toggle_selection]
        if items is None or len(items) == 1:
            data_type = self.data_type_singular
        else:
            data_type = self.data_type_plural
        return _("%(action)s %(data_type)s") % {
            'action': action,
            'data_type': data_type
        }

    def action(self, request, datum_id):
        """
        Required. Accepts a single object id and performs the specific action.

        Return values are discarded, errors raised are caught and logged.
        """
        raise NotImplementedError('action() must be defined for '
                                  'BatchAction: %s' % self.data_type_singular)

    def update(self, request, datum):
        """
        Switches the action verbose name, if needed
        """
        if getattr(self, 'action_present', False):
            self.verbose_name = self._conjugate()
            self.verbose_name_plural = self._conjugate('plural')

    def get_success_url(self, request=None):
        """
        Returns the URL to redirect to after a successful action.
        """
        if self.success_url:
            return self.success_url
        return request.get_full_path()

    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or _("N/A")
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.info('Permission denied to %s: "%s"' %
                         (self._conjugate(past=True).lower(), datum_display))
                continue
            try:
                self.action(request, datum_id)
                #Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info('%s: "%s"' %
                         (self._conjugate(past=True), datum_display))
            except Exception, ex:
                # Handle the exception but silence it since we'll display
                # an aggregate error message later. Otherwise we'd get
                # multiple error messages displayed to the user.
                if getattr(ex, "_safe_message", None):
                    ignore = False
                else:
                    ignore = True
                    action_failure.append(datum_display)
                exceptions.handle(request, ignore=ignore)

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You do not have permission to %(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_not_allowed).lower(),
                "objs": functions.lazy_join(", ", action_not_allowed)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_failure).lower(),
                "objs": functions.lazy_join(", ", action_failure)
            }
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {
                "action": self._conjugate(action_success, True),
                "objs": functions.lazy_join(", ", action_success)
            }
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))
示例#14
0
    def handle(self, table, request, obj_ids):
        action_success = []
        action_failure = []
        action_not_allowed = []
        for datum_id in obj_ids:
            datum = table.get_object_by_id(datum_id)
            datum_display = table.get_object_display(datum) or datum_id
            if not table._filter_action(self, request, datum):
                action_not_allowed.append(datum_display)
                LOG.warning(u'Permission denied to %(name)s: "%(dis)s"', {
                    'name': self._get_action_name(past=True).lower(),
                    'dis': datum_display
                })
                continue
            try:
                self.action(request, datum_id)
                # Call update to invoke changes if needed
                self.update(request, datum)
                action_success.append(datum_display)
                self.success_ids.append(datum_id)
                LOG.info(u'%(action)s: "%(datum_display)s"',
                         {'action': self._get_action_name(past=True),
                          'datum_display': datum_display})
            except Exception as ex:
                handled_exc = isinstance(ex, exceptions.HandledException)
                if handled_exc:
                    # In case of HandledException, an error message should be
                    # handled in exceptions.handle() or other logic,
                    # so we don't need to handle the error message here.
                    # NOTE(amotoki): To raise HandledException from the logic,
                    # pass escalate=True and do not pass redirect argument
                    # to exceptions.handle().
                    # If an exception is handled, the original exception object
                    # is stored in ex.wrapped[1].
                    ex = ex.wrapped[1]
                else:
                    # Handle the exception but silence it since we'll display
                    # an aggregate error message later. Otherwise we'd get
                    # multiple error messages displayed to the user.
                    action_failure.append(datum_display)
                action_description = (
                    self._get_action_name(past=True).lower(), datum_display)
                LOG.warning(
                    'Action %(action)s Failed for %(reason)s', {
                        'action': action_description, 'reason': ex})

        # Begin with success message class, downgrade to info if problems.
        success_message_level = messages.success
        if action_not_allowed:
            msg = _('You are not allowed to %(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_not_allowed).lower(),
                      "objs": functions.lazy_join(", ", action_not_allowed)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_failure:
            msg = _('Unable to %(action)s: %(objs)s')
            params = {"action": self._get_action_name(action_failure).lower(),
                      "objs": functions.lazy_join(", ", action_failure)}
            messages.error(request, msg % params)
            success_message_level = messages.info
        if action_success:
            msg = _('%(action)s: %(objs)s')
            params = {"action":
                      self._get_action_name(action_success, past=True),
                      "objs": functions.lazy_join(", ", action_success)}
            success_message_level(request, msg % params)

        return shortcuts.redirect(self.get_success_url(request))