How to use the webob.exc 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 Pylons / webob / tests / test_exc.py View on Github external
def method_not_allowed_app(req):
    if req.method != "GET":
        raise webob_exc.HTTPMethodNotAllowed()
    return "hello!"
github midokura / midonet-openstack / src / midolman / quantum / plugin.py View on Github external
net = super(MidonetPluginV2, self).get_network(context,
                                           subnet['subnet']['network_id'],
                                           fields=None)
        if net['subnets']:
            raise q_exc.NotImplementedError(
                    'MidoNet doesn\'t support multiple subnets '
                    'on the same network.')

        session = context.session
        with session.begin(subtransactions=True):
            sn_entry = super(MidonetPluginV2, self).create_subnet(context,
                             subnet)

            try:
                bridge = self.mido_mgmt.get_bridge(sn_entry['network_id'])
            except w_exc.HTTPNotFound as e:
                raise MidonetResourceNotFound(resource_type='Bridge',
                                              id=sn_entry['network_id'])

            gateway_ip = subnet['subnet']['gateway_ip']
            network_address, prefix = subnet['subnet']['cidr'].split('/')
            bridge.add_dhcp_subnet().default_gateway(gateway_ip)\
                                    .subnet_prefix(network_address)\
                                    .subnet_length(prefix).create()

            # If the network is externel, link the bridge to MidoNet provider
            # router
            self._extend_network_dict_l3(context, net)
            if net['router:external']:
                gateway_ip = sn_entry['gateway_ip']
                network_address, length = sn_entry['cidr'].split('/')
github openstack / glance / glance / api / v2 / metadef_tags.py View on Github external
def show(self, req, namespace, tag_name):
        meta_tag_repo = self.gateway.get_metadef_tag_repo(req.context)
        try:
            metadef_tag = meta_tag_repo.get(namespace, tag_name)
            return MetadefTag.to_wsme_model(metadef_tag)
        except exception.Forbidden as e:
            LOG.debug("User not permitted to show metadata tag '%s' "
                      "within '%s' namespace", tag_name, namespace)
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(encodeutils.exception_to_unicode(e))
            raise webob.exc.HTTPInternalServerError()
github openstack / neutron / quantum / wsgi.py View on Github external
msg = _("Malformed request body")
            LOG.exception(_("MalformedRequestBody: %s"), msg)
            return Fault(webob.exc.HTTPBadRequest(explanation=msg),
                         self._xmlns)

        try:
            action_result = self.dispatch(request, action, args)
        except webob.exc.HTTPException as ex:
            LOG.info(_("HTTP exception thrown: %s"), unicode(ex))
            action_result = Fault(ex,
                                  self._xmlns,
                                  self._fault_body_function)
        except Exception:
            LOG.exception(_("Internal error"))
            # Do not include the traceback to avoid returning it to clients.
            action_result = Fault(webob.exc.HTTPServerError(),
                                  self._xmlns,
                                  self._fault_body_function)

        if isinstance(action_result, dict) or action_result is None:
            response = self.serializer.serialize(action_result,
                                                 accept,
                                                 action=action)
        else:
            response = action_result

        try:
            msg_dict = dict(url=request.url, status=response.status_int)
            msg = _("%(url)s returned with HTTP %(status)d") % msg_dict
        except AttributeError as e:
            msg_dict = dict(url=request.url, exception=e)
            msg = _("%(url)s returned a fault: %(exception)s") % msg_dict
github openstack / karbor / karbor / api / v1 / restores.py View on Github external
def _restore_get(self, context, restore_id):
        if not uuidutils.is_uuid_like(restore_id):
            msg = _("Invalid restore id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        restore = objects.Restore.get_by_id(context, restore_id)
        try:
            context.can(restore_policy.GET_POLICY, restore)
        except exception.PolicyNotAuthorized:
            # raise RestoreNotFound instead to make sure karbor behaves
            # as it used to
            raise exception.RestoreNotFound(restore_id=restore_id)
        LOG.info("Restore info retrieved successfully.")
        return restore
github apache / allura / Allura / allura / ext / admin / admin_main.py View on Github external
`{"status": "in progress", "filename": FILENAME}` will be returned,
        where `FILENAME` is the filename of the export artifact relative to
        the users shell account directory.
        """
        if not asbool(config.get('bulk_export_enabled', True)):
            raise exc.HTTPNotFound()
        if not tools:
            raise exc.HTTPBadRequest(
                'Must give at least one tool mount point to export')
        tools = aslist(tools, ',')
        exportable_tools = AdminApp.exportable_tools_for(c.project)
        allowed = set(t.options.mount_point for t in exportable_tools)
        if not set(tools).issubset(allowed):
            raise exc.HTTPBadRequest('Invalid tool')
        if c.project.bulk_export_status() == 'busy':
            raise exc.HTTPServiceUnavailable(
                'Export for project %s already running' % c.project.shortname)
        # filename (potentially) includes a timestamp, so we have
        # to pre-generate to be able to return it to the user
        filename = c.project.bulk_export_filename()
        export_tasks.bulk_export.post(tools, filename, send_email=send_email, with_attachments=with_attachments)
        return {
            'status': 'in progress',
            'filename': filename,
        }
github apache / allura / Allura / allura / lib / decorators.py View on Github external
def _wrapper(self, *args, **kwargs):
        result = None
        try:
            try:
                result = self._func(*args, **kwargs)
            except exc.HTTPServerError:
                raise
            except exc.HTTPException, e:
                result = e
            args = self._args
            kwargs = self._kwargs
            extra = kwargs.setdefault('extra', {})
            extra.update(self._make_extra(result))
            self._logger.log(self._level, self._msg,
                             *self._args, **self._kwargs)
            return result
        except:
            args = self._args
            kwargs = self._kwargs
            extra = kwargs.setdefault('extra', {})
            extra.update(self._make_extra(result))
            kwargs['exc_info'] = sys.exc_info()
github ButterFlyDevs / StudentsManagementSystem / google_appengine / google / appengine / ext / ndb / tasklets.py View on Github external
def _init_flow_exceptions():
  """Internal helper to initialize _flow_exceptions.

  This automatically adds webob.exc.HTTPException, if it can be imported.
  """
  global _flow_exceptions
  _flow_exceptions = ()
  add_flow_exception(datastore_errors.Rollback)
  try:
    from webob import exc
  except ImportError:
    pass
  else:
    add_flow_exception(exc.HTTPException)
github openstack / nova / nova / api / metadata / handler.py View on Github external
instance_id,
            hashlib.sha256).hexdigest()

        if not utils.constant_time_compare(expected_signature, signature):
            if instance_id:
                LOG.warn(_LW('X-Instance-ID-Signature: %(signature)s does '
                             'not match the expected value: '
                             '%(expected_signature)s for id: %(instance_id)s.'
                             '  Request From: %(remote_address)s'),
                         {'signature': signature,
                          'expected_signature': expected_signature,
                          'instance_id': instance_id,
                          'remote_address': remote_address})

            msg = _('Invalid proxy request signature.')
            raise webob.exc.HTTPForbidden(explanation=msg)

        try:
            meta_data = self.get_metadata_by_instance_id(instance_id,
                                                         remote_address)
        except Exception:
            LOG.exception(_LE('Failed to get metadata for instance id: %s'),
                          instance_id)
            msg = _('An unknown error has occurred. '
                    'Please try your request again.')
            raise webob.exc.HTTPInternalServerError(
                                               explanation=six.text_type(msg))

        if meta_data is None:
            LOG.error(_LE('Failed to get metadata for instance id: %s'),
                      instance_id)
        elif meta_data.instance['project_id'] != tenant_id:
github StackStorm / st2 / st2common / st2common / hooks.py View on Github external
def on_error(self, state, e):
        if hasattr(e, 'body') and isinstance(e.body, dict):
            body = e.body
        else:
            body = {}

        if isinstance(e, exc.HTTPException):
            status_code = state.response.status
            message = str(e)
        elif isinstance(e, db_exceptions.StackStormDBObjectNotFoundError):
            status_code = httplib.NOT_FOUND
            message = str(e)
        elif isinstance(e, db_exceptions.StackStormDBObjectConflictError):
            status_code = httplib.CONFLICT
            message = str(e)
            body['conflict-id'] = e.conflict_id
        elif isinstance(e, rbac_exceptions.AccessDeniedError):
            status_code = httplib.FORBIDDEN
            message = str(e)
        elif isinstance(e, (ValueValidationException, ValueError, mongoengine.ValidationError)):
            status_code = httplib.BAD_REQUEST
            message = getattr(e, 'message', str(e))
        else: