当前位置: 首页>>代码示例>>Python>>正文


Python exc.HTTPForbidden方法代码示例

本文整理汇总了Python中webob.exc.HTTPForbidden方法的典型用法代码示例。如果您正苦于以下问题:Python exc.HTTPForbidden方法的具体用法?Python exc.HTTPForbidden怎么用?Python exc.HTTPForbidden使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在webob.exc的用法示例。


在下文中一共展示了exc.HTTPForbidden方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __call__

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def __call__(self, req):
        path = os.path.abspath(os.path.join(self.path,
                                            req.path_info.lstrip('/')))
        if os.path.isdir(path) and self.index_page:
            return self.index(req, path)
        if (self.index_page and self.hide_index_with_redirect
            and path.endswith(os.path.sep + self.index_page)):
            new_url = req.path_url.rsplit('/', 1)[0]
            new_url += '/'
            if req.query_string:
                new_url += '?' + req.query_string
            return Response(
                status=301,
                location=new_url)
        if not os.path.isfile(path):
            return exc.HTTPNotFound(comment=path)
        elif not path.startswith(self.path):
            return exc.HTTPForbidden()
        else:
            return self.make_fileapp(path) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:22,代码来源:static.py

示例2: delete

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def delete(self, req, id):
        """Delete a security service."""
        context = req.environ['manila.context']

        LOG.info("Delete security service with id: %s",
                 id, context=context)

        try:
            security_service = db.security_service_get(context, id)
        except exception.NotFound:
            raise exc.HTTPNotFound()

        share_nets = db.share_network_get_all_by_security_service(
            context, id)
        if share_nets:
            msg = _("Cannot delete security service. It is "
                    "assigned to share network(s)")
            raise exc.HTTPForbidden(explanation=msg)
        policy.check_policy(context, RESOURCE_NAME,
                            'delete', security_service)
        db.security_service_delete(context, id)

        return webob.Response(status_int=http_client.ACCEPTED) 
开发者ID:openstack,项目名称:manila,代码行数:25,代码来源:security_service.py

示例3: delete

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def delete(self, req, id):
        """Delete specified share server."""
        context = req.environ['manila.context']
        try:
            share_server = db_api.share_server_get(context, id)
        except exception.ShareServerNotFound as e:
            raise exc.HTTPNotFound(explanation=e.msg)
        allowed_statuses = [constants.STATUS_ERROR, constants.STATUS_ACTIVE]
        if share_server['status'] not in allowed_statuses:
            data = {
                'status': share_server['status'],
                'allowed_statuses': allowed_statuses,
            }
            msg = _("Share server's actual status is %(status)s, allowed "
                    "statuses for deletion are %(allowed_statuses)s.") % (data)
            raise exc.HTTPForbidden(explanation=msg)
        LOG.debug("Deleting share server with id: %s.", id)
        try:
            self.share_api.delete_share_server(context, share_server)
        except exception.ShareServerInUse as e:
            raise exc.HTTPConflict(explanation=e.msg)
        return webob.Response(status_int=http_client.ACCEPTED) 
开发者ID:openstack,项目名称:manila,代码行数:24,代码来源:share_servers.py

示例4: promote

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def promote(self, req, id, body):
        """Promote a replica to active state."""
        context = req.environ['manila.context']

        try:
            replica = db.share_replica_get(context, id)
        except exception.ShareReplicaNotFound:
            msg = _("No replica exists with ID %s.")
            raise exc.HTTPNotFound(explanation=msg % id)

        replica_state = replica.get('replica_state')

        if replica_state == constants.REPLICA_STATE_ACTIVE:
            return webob.Response(status_int=http_client.OK)

        try:
            replica = self.share_api.promote_share_replica(context, replica)
        except exception.ReplicationException as e:
            raise exc.HTTPBadRequest(explanation=six.text_type(e))
        except exception.AdminRequired as e:
            raise exc.HTTPForbidden(explanation=six.text_type(e))

        return self._view_builder.detail(req, replica) 
开发者ID:openstack,项目名称:manila,代码行数:25,代码来源:share_replicas.py

示例5: _show

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def _show(self, req, share_id, export_location_uuid,
              ignore_secondary_replicas=False):
        context = req.environ['manila.context']
        self._verify_share(context, share_id)
        try:
            export_location = db_api.share_export_location_get_by_uuid(
                context, export_location_uuid,
                ignore_secondary_replicas=ignore_secondary_replicas)
        except exception.ExportLocationNotFound:
            msg = _("Export location '%s' not found.") % export_location_uuid
            raise exc.HTTPNotFound(explanation=msg)

        if export_location.is_admin_only and not context.is_admin:
            raise exc.HTTPForbidden()

        return self._view_builder.detail(req, export_location) 
开发者ID:openstack,项目名称:manila,代码行数:18,代码来源:share_export_locations.py

示例6: _remove_security_service

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def _remove_security_service(self, req, id, data):
        """Dissociate share network from a given security service."""
        context = req.environ['manila.context']
        policy.check_policy(context, RESOURCE_NAME, 'remove_security_service')
        share_network = db_api.share_network_get(context, id)

        if self._share_network_subnets_contain_share_servers(share_network):
            msg = _("Cannot remove security services. Share network is used.")
            raise exc.HTTPForbidden(explanation=msg)
        try:
            share_network = db_api.share_network_remove_security_service(
                context,
                id,
                data['security_service_id'])
        except KeyError:
            msg = "Malformed request body"
            raise exc.HTTPBadRequest(explanation=msg)
        except exception.NotFound as e:
            raise exc.HTTPNotFound(explanation=six.text_type(e))
        except exception.ShareNetworkSecurityServiceDissociationError as e:
            raise exc.HTTPBadRequest(explanation=six.text_type(e))

        return self._view_builder.build_share_network(req, share_network) 
开发者ID:openstack,项目名称:manila,代码行数:25,代码来源:share_networks.py

示例7: test_policy_not_authorized

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def test_policy_not_authorized(self, method_name):

        method = getattr(self.controller, method_name)
        arguments = {
            'id': 'FAKE_REPLICA_ID',
            'body': {'FAKE_KEY': 'FAKE_VAL'},
        }
        if method_name in ('index', 'detail'):
            arguments.clear()

        noauthexc = exception.PolicyNotAuthorized(action=six.text_type(method))

        with mock.patch.object(
                policy, 'check_policy', mock.Mock(side_effect=noauthexc)):

            self.assertRaises(
                exc.HTTPForbidden, method, self.replicas_req, **arguments) 
开发者ID:openstack,项目名称:manila,代码行数:19,代码来源:test_share_replicas.py

示例8: test_policy_not_authorized

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def test_policy_not_authorized(self, method_name):

        method = getattr(self.controller, method_name)
        if method_name in ('index', 'detail'):
            arguments = {}
        else:
            arguments = {
                'id': 'FAKE_SNAPSHOT_ID',
                'body': {'FAKE_KEY': 'FAKE_VAL'},
            }

        noauthexc = exception.PolicyNotAuthorized(action=six.text_type(method))

        with mock.patch.object(
                policy, 'check_policy', mock.Mock(side_effect=noauthexc)):

            self.assertRaises(
                exc.HTTPForbidden, method, self.snapshot_instances_req,
                **arguments) 
开发者ID:openstack,项目名称:manila,代码行数:21,代码来源:test_share_snapshot_instances.py

示例9: test_update_invalid_key_in_use

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def test_update_invalid_key_in_use(self):
        share_nw = fake_share_network.copy()
        subnet = fake_share_network_subnet.copy()
        subnet['share_servers'] = [{'id': 1}]
        share_nw['share_network_subnets'] = [subnet]

        db_api.share_network_get.return_value = share_nw
        body = {
            share_networks.RESOURCE_NAME: {
                'name': 'new name',
                'user_id': 'new id',
            },
        }
        self.assertRaises(webob_exc.HTTPForbidden,
                          self.controller.update,
                          self.req,
                          share_nw['id'],
                          body) 
开发者ID:openstack,项目名称:manila,代码行数:20,代码来源:test_share_networks.py

示例10: test_action_remove_security_service_forbidden

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def test_action_remove_security_service_forbidden(self):
        share_network = fake_share_network.copy()
        subnet = fake_share_network_subnet.copy()
        subnet['share_servers'] = ['foo']
        share_network['share_network_subnets'] = [subnet]
        db_api.share_network_get.return_value = share_network
        self.mock_object(
            self.controller, '_share_network_subnets_contain_share_servers',
            mock.Mock(return_value=True))
        body = {
            'remove_security_service': {
                'security_service_id': 'fake id',
            },
        }
        self.assertRaises(webob_exc.HTTPForbidden,
                          self.controller.action,
                          self.req,
                          share_network['id'],
                          body)
        db_api.share_network_get.assert_called_once_with(
            self.req.environ['manila.context'], share_network['id'])
        share_networks.policy.check_policy.assert_called_once_with(
            self.req.environ['manila.context'],
            share_networks.RESOURCE_NAME,
            'remove_security_service') 
开发者ID:openstack,项目名称:manila,代码行数:27,代码来源:test_share_networks.py

示例11: _assert_fail_rbac

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def _assert_fail_rbac(self, roles, method_under_test, accept=None,
                          content_type=None, user_id=None, project_id=None):
        """Assert that RBAC rules failed for one of the specified roles.

        :param roles: List of roles to check, one at a time
        :param method_under_test: The test method to invoke for each role.
        :param accept Optional Accept header to set on the HTTP request
        :return: None
        """
        for role in roles:
            self.req = self._generate_req(roles=[role] if role else [],
                                          accept=accept,
                                          content_type=content_type,
                                          user_id=user_id,
                                          project_id=project_id)

            exception = self.assertRaises(exc.HTTPForbidden, method_under_test)
            self.assertEqual(403, exception.status_int) 
开发者ID:cloud-security-research,项目名称:sgx-kms,代码行数:20,代码来源:test_resources_policy.py

示例12: policy_enforce

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def policy_enforce(handler):
    """Decorator that enforces policies.

    Check the path matches the request context and enforce policy defined in
    policy file and policies in code.

    This is a handler method decorator.
    """
    @functools.wraps(handler)
    def policy_checker(controller, req, **kwargs):
        # Enable project_id based target check
        rule = "%s:%s" % (controller.REQUEST_SCOPE,
                          handler.__name__)
        allowed = policy.enforce(context=req.context, rule=rule, target={})
        if not allowed:
            raise exc.HTTPForbidden()
        return handler(controller, req, **kwargs)

    return policy_checker 
开发者ID:openstack,项目名称:senlin,代码行数:21,代码来源:util.py

示例13: require

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def require(predicate, message=None):
    '''
    Example: ``require(has_access(c.app, 'read'))``

    :param callable predicate: truth function to call
    :param str message: message to show upon failure
    :raises: HTTPForbidden or HTTPUnauthorized
    '''

    from allura import model as M
    if predicate():
        return
    if not message:
        message = """You don't have permission to do that.
                     You must ask a project administrator for rights to perform this task.
                     Please click the back button to return to the previous page."""
    if c.user != M.User.anonymous():
        request.environ['error_message'] = message
        raise exc.HTTPForbidden(detail=message)
    else:
        raise exc.HTTPUnauthorized() 
开发者ID:apache,项目名称:allura,代码行数:23,代码来源:security.py

示例14: perform_import

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def perform_import(
            self, doc=None, username_mapping=None, default_username=None, create_users=False,
            **kw):
        require_access(c.project, 'admin')
        if username_mapping is None:
            username_mapping = '{}'
        if not c.api_token.can_import_forum():
            log.error('Import capability is not enabled for %s', c.project.shortname)
            raise exc.HTTPForbidden(detail='Import is not allowed')
        try:
            doc = json.loads(doc)
            username_mapping = json.loads(username_mapping)
            warnings = import_support.perform_import(
                doc, username_mapping, default_username, create_users)
            return dict(warnings=warnings, errors=[])
        except Exception as e:
            raise
            log.exception(e)
            return dict(status=False, errors=[str(e)]) 
开发者ID:apache,项目名称:allura,代码行数:21,代码来源:root.py

示例15: testErrorHandling_UpvoteRequestHandler_WithRequestCounter

# 需要导入模块: from webob import exc [as 别名]
# 或者: from webob.exc import HTTPForbidden [as 别名]
def testErrorHandling_UpvoteRequestHandler_WithRequestCounter(
      self, mock_dispatch, mock_handle_exception, mock_grc):

    # Mocking out the call to dispatch(), because any exceptions that occur
    # within the bulk of that method (or in an override of dispatch() by us, for
    # example, in SantaRequestHandler) aren't caught by the handle_exception()
    # method.
    # Rather, they bubble up to the WSGIApplication.error_handlers.
    mock_dispatch.side_effect = exc.HTTPForbidden
    mock_metric = mock.Mock()
    mock_grc.return_value = mock_metric

    response = self.testapp.get('/', expect_errors=True)

    self.assertEqual(httplib.FORBIDDEN, response.status_int)
    self.assertEqual(1, mock_dispatch.call_count)
    self.assertEqual(0, mock_handle_exception.call_count)
    self.assertEqual(1, mock_grc.call_count)
    self.assertEqual(1, mock_metric.Increment.call_count)
    self.assertEqual(httplib.FORBIDDEN, mock_metric.Increment.call_args[0][0]) 
开发者ID:google,项目名称:upvote,代码行数:22,代码来源:handler_utils_test.py


注:本文中的webob.exc.HTTPForbidden方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。