How to use the webob.exc.HTTPBadRequest 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 / gce-api / gceapi / api / wsgi.py View on Github external
raise GCEFault(webob.exc.HTTPBadRequest(
                    explanation=msg))
            except exception.MalformedRequestBody:
                msg = _("Malformed request body")
                raise GCEFault(webob.exc.HTTPBadRequest(
                    explanation=msg))

            # Now, deserialize the request body...
            try:
                if content_type:
                    contents = self.deserialize(method, content_type, body)
                else:
                    contents = {}
            except exception.InvalidContentType:
                msg = _("Unsupported Content-Type")
                raise GCEFault(webob.exc.HTTPBadRequest(
                    explanation=msg))
            except exception.MalformedRequestBody:
                msg = _("Malformed request body")
                raise GCEFault(webob.exc.HTTPBadRequest(
                    explanation=msg))

            # Update the action args
            action_args.update(contents)

            # Check project
            project_id = action_args.pop("project_id", None)
            context = request.environ.get('gceapi.context')
            action_result = self._check_requested_project(project_id, context)

            if action_result is None:
                with GCEResourceExceptionHandler():
github openstack / nova / nova / api / openstack / identity.py View on Github external
try:
        resp = sess.get('/v3/projects/%s' % project_id,
                        endpoint_filter={'service_type': 'identity'},
                        raise_exc=False)
    except kse.ClientException:
        # something is wrong, like there isn't a keystone v3 endpoint,
        # we'll take the pass and default to everything being ok.
        LOG.exception("Unable to contact keystone to verify project_id")
        return True

    if resp:
        # All is good with this 20x status
        return True
    elif resp.status_code == 404:
        # we got access, and we know this project is not there
        raise webob.exc.HTTPBadRequest(
            explanation=_("Project ID %s is not a valid project.") %
            project_id)
    elif resp.status_code == 403:
        # we don't have enough permission to verify this, so default
        # to "it's ok".
        LOG.info(
            "Insufficient permissions for user %(user)s to verify "
            "existence of project_id %(pid)s",
            {"user": context.user_id, "pid": project_id})
        return True
    else:
        LOG.warning(
            "Unexpected response from keystone trying to "
            "verify project_id %(pid)s - resp: %(code)s %(content)s",
            {"pid": project_id,
             "code": resp.status_code,
github openstack / cinder / cinder / api / v3 / volume_transfer.py View on Github external
name = transfer.get('name', None)
        if name is not None:
            name = name.strip()

        no_snapshots = strutils.bool_from_string(transfer.get('no_snapshots',
                                                              False))

        LOG.info("Creating transfer of volume %s", volume_id)

        try:
            new_transfer = self.transfer_api.create(context, volume_id, name,
                                                    no_snapshots=no_snapshots)
        # Not found exception will be handled at the wsgi level
        except exception.Invalid as error:
            raise exc.HTTPBadRequest(explanation=error.msg)

        transfer = self._view_builder.create(req,
                                             dict(new_transfer))
        return transfer
github openstack / glance / glance / api / v2 / images.py View on Github external
exception.ReadonlyProperty) as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug("User not permitted to create image")
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.LimitExceeded as e:
            LOG.warn(encodeutils.exception_to_unicode(e))
            raise webob.exc.HTTPRequestEntityTooLarge(
                explanation=e.msg, request=req, content_type='text/plain')
        except exception.Duplicate as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except exception.NotAuthenticated as e:
            raise webob.exc.HTTPUnauthorized(explanation=e.msg)
        except TypeError as e:
            LOG.debug(encodeutils.exception_to_unicode(e))
            raise webob.exc.HTTPBadRequest(explanation=e)

        return image
github openstack / glance / glance / registry / api / v1 / images.py View on Github external
def _get_is_public(self, req):
        """Parse is_public into something usable."""
        is_public = req.params.get('is_public')

        if is_public is None:
            # NOTE(vish): This preserves the default value of showing only
            #             public images.
            return True
        elif is_public.lower() == 'none':
            return None

        value = self._get_bool(is_public)
        if value is None:
            raise exc.HTTPBadRequest(_("is_public must be None, True, or "
                                       "False"))

        return value
github Pylons / webob / docs / wiki-example-code / example.py View on Github external
def __call__(self, environ, start_response):
        req = Request(environ)
        action = req.params.get('action', 'view')
        page = self.get_page(req.path_info)
        try:
            try:
                meth = getattr(self, 'action_%s_%s' % (action, req.method))
            except AttributeError:
                raise exc.HTTPBadRequest('No such action %r' % action)
            resp = meth(req, page)
        except exc.HTTPException, e:
            resp = e
        return resp(environ, start_response)
github openstack / nova / nova / api / openstack / compute / plugins / v3 / flavors.py View on Github external
context = req.environ['nova.context']
        if context.is_admin:
            # Only admin has query access to all flavor types
            filters['is_public'] = self._parse_is_public(
                    req.params.get('is_public', None))
        else:
            filters['is_public'] = True
            filters['disabled'] = False

        if 'min_ram' in req.params:
            try:
                filters['min_memory_mb'] = int(req.params['min_ram'])
            except ValueError:
                msg = _('Invalid min_ram filter [%s]') % req.params['min_ram']
                raise webob.exc.HTTPBadRequest(explanation=msg)

        if 'min_disk' in req.params:
            try:
                filters['min_root_gb'] = int(req.params['min_disk'])
            except ValueError:
                msg = (_('Invalid min_disk filter [%s]') %
                       req.params['min_disk'])
                raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            limited_flavors = flavors.get_all_flavors_sorted_list(context,
                filters=filters, sort_key=sort_key, sort_dir=sort_dir,
                limit=limit, marker=marker)
        except exception.MarkerNotFound:
            msg = _('marker [%s] not found') % marker
            raise webob.exc.HTTPBadRequest(explanation=msg)
github openstack / manila / manila / api / v2 / share_servers.py View on Github external
if share_utils.extract_host(host, 'pool'):
            msg = _("Host parameter should not contain pool.")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            utils.validate_service_host(
                context, share_utils.extract_host(host))
        except exception.ServiceNotFound as e:
            raise exc.HTTPBadRequest(explanation=e)
        except exception.PolicyNotAuthorized as e:
            raise exc.HTTPForbidden(explanation=e)
        except exception.AdminRequired as e:
            raise exc.HTTPForbidden(explanation=e)
        except exception.ServiceIsDown as e:
            raise exc.HTTPBadRequest(explanation=e)

        try:
            share_network = db_api.share_network_get(
                context, share_network_id)
        except exception.ShareNetworkNotFound as e:
            raise exc.HTTPBadRequest(explanation=e)

        driver_opts = data.get('driver_options')
        if driver_opts is not None and not isinstance(driver_opts, dict):
            msg = _("Driver options must be in dictionary format.")
            raise exc.HTTPBadRequest(explanation=msg)

        return identifier, host, share_network, driver_opts, network_subnet
github openstack / glance / glance / api / v2 / image_data.py View on Github external
except glance_store.StorageWriteDenied as e:
            msg = _("Insufficient permissions on image "
                    "storage media: %s") % encodeutils.exception_to_unicode(e)
            LOG.error(msg)
            self._restore(image_repo, image)
            raise webob.exc.HTTPServiceUnavailable(explanation=msg,
                                                   request=req)

        except cursive_exception.SignatureVerificationError as e:
            msg = (_LE("Signature verification failed for image %(id)s: %(e)s")
                   % {'id': image_id,
                      'e': encodeutils.exception_to_unicode(e)})
            LOG.error(msg)
            self._delete(image_repo, image)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        except webob.exc.HTTPGone:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Failed to upload image data due to HTTP error"))

        except webob.exc.HTTPError:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Failed to upload image data due to HTTP error"))
                self._restore(image_repo, image)

        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Failed to upload image data due to "
                              "internal error"))
                self._restore(image_repo, image)
github openstack / trove / trove / common / wsgi.py View on Github external
webob.exc.HTTPUnprocessableEntity: [
            exception.UnprocessableEntity,
        ],
        webob.exc.HTTPUnauthorized: [
            exception.Forbidden,
            exception.SwiftAuthError,
        ],
        webob.exc.HTTPForbidden: [
            exception.ReplicaSourceDeleteForbidden,
            exception.BackupTooLarge,
            exception.ModuleAccessForbidden,
            exception.ModuleAppliedToInstance,
            exception.PolicyNotAuthorized,
            exception.LogAccessForbidden,
        ],
        webob.exc.HTTPBadRequest: [
            exception.InvalidModelError,
            exception.BadRequest,
            exception.CannotResizeToSameSize,
            exception.BadValue,
            exception.DatabaseAlreadyExists,
            exception.UserAlreadyExists,
            exception.LocalStorageNotSpecified,
            exception.ModuleAlreadyExists,
        ],
        webob.exc.HTTPNotFound: [
            exception.NotFound,
            exception.ComputeInstanceNotFound,
            exception.ModelNotFoundError,
            exception.UserNotFound,
            exception.DatabaseNotFound,
            exception.QuotaResourceUnknown,