How to use the webob.exc.HTTPConflict function in WebOb

To help you get started, we’ve selected a few WebOb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / nova / nova / api / openstack / compute / legacy_v2 / contrib / admin_actions.py View on Github external
def _pause(self, req, id, body):
        """Permit Admins to pause the server."""
        ctxt = req.environ['nova.context']
        authorize(ctxt, 'pause')
        server = common.get_instance(self.compute_api, ctxt, id)
        try:
            self.compute_api.pause(ctxt, server)
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'pause', id)
        except exception.InstanceNotFound:
            msg = _("Server not found")
            raise exc.HTTPNotFound(explanation=msg)
        except Exception:
            readable = traceback.format_exc()
            LOG.exception(_LE("Compute.api::pause %s"), readable)
            raise exc.HTTPUnprocessableEntity()
        return webob.Response(status_int=202)
github openstack / glance / glance / cmd / replicator.py View on Github external
explanation=response.read())

        if code == http.INTERNAL_SERVER_ERROR:
            raise exc.HTTPInternalServerError(
                explanation=response.read())

        if code == http.UNAUTHORIZED:
            raise exc.HTTPUnauthorized(
                explanation=response.read())

        if code == http.FORBIDDEN:
            raise exc.HTTPForbidden(
                explanation=response.read())

        if code == http.CONFLICT:
            raise exc.HTTPConflict(
                explanation=response.read())

        if ignore_result_body:
            # NOTE: because we are pipelining requests through a single HTTP
            # connection, http_client requires that we read the response body
            # before we can make another request. If the caller knows they
            # don't care about the body, they can ask us to do that for them.
            response.read()
        return response
github openstack / manila / manila / api / contrib / share_type_access.py View on Github external
project = body['addProjectAccess']['project']

        try:
            share_type = share_types.get_share_type(context, id)

            if share_type['is_public']:
                msg = _("You cannot add project to public share_type.")
                raise webob.exc.HTTPForbidden(explanation=msg)

        except exception.ShareTypeNotFound as err:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))

        try:
            share_types.add_share_type_access(context, id, project)
        except exception.ShareTypeAccessExists as err:
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))

        return webob.Response(status_int=202)
github openstack / nova / nova / api / openstack / compute / security_group_default_rules.py View on Github external
from_port=sg_rule.get('from_port'),
                ip_protocol=sg_rule.get('ip_protocol'),
                cidr=sg_rule.get('cidr'))
        except (exception.InvalidCidr,
                exception.InvalidInput,
                exception.InvalidIpProtocol,
                exception.InvalidPortRange) as ex:
            raise exc.HTTPBadRequest(explanation=ex.format_message())

        if values is None:
            msg = _('Not enough parameters to build a valid rule.')
            raise exc.HTTPBadRequest(explanation=msg)

        if self.security_group_api.default_rule_exists(context, values):
            msg = _('This default rule already exists.')
            raise exc.HTTPConflict(explanation=msg)
        security_group_rule = self.security_group_api.add_default_rules(
            context, [values])[0]
        fmt_rule = self._format_security_group_default_rule(
                                                        security_group_rule)
        return {'security_group_default_rule': fmt_rule}
github openstack / manila / manila / api / v2 / shares.py View on Github external
}
                msg = _("Share %(share_id)s is in '%(state)s' state, but it "
                        "must be in '%(available)s' state to be reverted to a "
                        "snapshot.")
                raise exc.HTTPConflict(explanation=msg % msg_args)

            # Ensure snapshot status is 'available'.
            if snapshot['status'] != constants.STATUS_AVAILABLE:
                msg_args = {
                    'snap_id': snapshot_id,
                    'state': snapshot['status'],
                    'available': constants.STATUS_AVAILABLE,
                }
                msg = _("Snapshot %(snap_id)s is in '%(state)s' state, but it "
                        "must be in '%(available)s' state to be restored.")
                raise exc.HTTPConflict(explanation=msg % msg_args)

            # Ensure a long-running task isn't active on the share
            if share.is_busy:
                msg_args = {'share_id': share_id}
                msg = _("Share %(share_id)s may not be reverted while it has "
                        "an active task.")
                raise exc.HTTPConflict(explanation=msg % msg_args)

            # Ensure the snapshot is the most recent one.
            latest_snapshot = self.share_api.get_latest_snapshot_for_share(
                context, share_id)
            if not latest_snapshot:
                msg_args = {'share_id': share_id}
                msg = _("Could not determine the latest snapshot for share "
                        "%(share_id)s.")
                raise exc.HTTPBadRequest(explanation=msg % msg_args)
github openstack / manila / manila / api / v2 / share_group_types.py View on Github external
def _assert_non_public_share_group_type(self, context, type_id):
        try:
            share_group_type = share_group_types.get(
                context, type_id)
            if share_group_type['is_public']:
                msg = _("Type access modification is not applicable to "
                        "public share group type.")
                raise webob.exc.HTTPConflict(explanation=msg)
        except exception.ShareGroupTypeNotFound as err:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))
github openstack / glance / glance / api / v1 / images.py View on Github external
location)
        else:
            # Ensure that the size attribute is set to zero for directly
            # uploadable images (if not provided). The size will be set
            # to a non-zero value during upload
            image_meta['size'] = image_meta.get('size', 0)

        try:
            image_meta = registry.add_image_metadata(req.context, image_meta)
            self.notifier.info("image.create", redact_loc(image_meta))
            return image_meta
        except exception.Duplicate:
            msg = (_("An image with identifier %s already exists") %
                   image_meta['id'])
            LOG.warn(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Invalid as e:
            msg = (_("Failed to reserve image. Got error: %s") %
                   encodeutils.exception_to_unicode(e))
            LOG.exception(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.Forbidden:
            msg = _("Forbidden to reserve image.")
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
github openstack / glance / glance / api / v2 / images.py View on Github external
LOG.debug("User not permitted to delete image '%s'", image_id)
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except (glance_store.NotFound, exception.NotFound):
            msg = (_("Failed to find image %(image_id)s to delete") %
                   {'image_id': image_id})
            LOG.warn(msg)
            raise webob.exc.HTTPNotFound(explanation=msg)
        except glance_store.exceptions.InUseByStore as e:
            msg = (_("Image %(id)s could not be deleted "
                     "because it is in use: %(exc)s") %
                   {"id": image_id,
                    "exc": e.msg})
            LOG.warn(msg)
            raise webob.exc.HTTPConflict(explanation=msg)
        except glance_store.exceptions.HasSnapshot as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except exception.InvalidImageStatusTransition as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        except exception.NotAuthenticated as e:
            raise webob.exc.HTTPUnauthorized(explanation=e.msg)
github SmartTeleMax / iktomi-cms / iktomi / cms / stream_handlers.py View on Github external
def watch_for_key(self, env, key, timeout=4):
        # XXX hack: timeout should be less than autosave interval,
        #     otherwise a conflict never ends
        with env.redis.pipeline() as pipe:
            try:
                # watching the key in redis to prevent same form
                # duplicate creation. Creating object only after
                # redis transaction completed successfully and if it
                # was first transaction
                pipe.watch(key)
                current_val = pipe.get(key)
                pipe.multi()
                pipe.set(key, 1, timeout)
                pipe.execute()
                if current_val is not None:
                    raise HTTPConflict
            except WatchError:
                raise HTTPConflict
github openstack / nova / nova / api / openstack / compute / legacy_v2 / contrib / console_output.py View on Github external
int(str(length))
            except ValueError:
                raise webob.exc.HTTPBadRequest(_('Length in request body must '
                                                 'be an integer value'))

        try:
            output = self.compute_api.get_console_output(context,
                                                         instance,
                                                         length)
        except exception.ConsoleNotAvailable as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.NotFound:
            msg = _('Unable to get console')
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            msg = _("Unable to get console log, functionality not implemented")
            raise webob.exc.HTTPNotImplemented(explanation=msg)

        # XML output is not correctly escaped, so remove invalid characters
        remove_re = re.compile('[\x00-\x08\x0B-\x1F]')
        output = remove_re.sub('', output)

        return {'output': output}