本文整理汇总了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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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')
示例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)
示例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
示例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()
示例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)])
示例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])