本文整理汇总了Python中rest_framework.exceptions.MethodNotAllowed方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.MethodNotAllowed方法的具体用法?Python exceptions.MethodNotAllowed怎么用?Python exceptions.MethodNotAllowed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.MethodNotAllowed方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_action
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def handle_action(self, action: str, request_id: str, **kwargs):
"""
run the action.
"""
try:
await self.check_permissions(action, **kwargs)
if action not in self.available_actions:
raise MethodNotAllowed(method=action)
method_name = self.available_actions[action]
method = getattr(self, method_name)
reply = partial(self.reply, action=action, request_id=request_id)
# the @action decorator will wrap non-async action into async ones.
response = await method(request_id=request_id, action=action, **kwargs)
if isinstance(response, tuple):
data, status = response
await reply(data=data, status=status)
except Exception as exc:
await self.handle_exception(exc, action=action, request_id=request_id)
示例2: post
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def post(self, request, *args, **kwargs):
related_instance_or_manager = self.get_related_instance()
if isinstance(related_instance_or_manager, Manager):
related_model_class = related_instance_or_manager.model
serializer = self.get_serializer(
data=request.data, model_class=related_model_class, many=True
)
serializer.is_valid(raise_exception=True)
if frozenset(serializer.validated_data) <= frozenset(related_instance_or_manager.all()):
return Response(status=204)
related_instance_or_manager.add(*serializer.validated_data)
else:
raise MethodNotAllowed('POST')
result_serializer = self._instantiate_serializer(related_instance_or_manager)
return Response(result_serializer.data)
示例3: delete
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def delete(self, request, *args, **kwargs):
related_instance_or_manager = self.get_related_instance()
if isinstance(related_instance_or_manager, Manager):
related_model_class = related_instance_or_manager.model
serializer = self.get_serializer(
data=request.data, model_class=related_model_class, many=True
)
serializer.is_valid(raise_exception=True)
objects = related_instance_or_manager.all()
if frozenset(serializer.validated_data).isdisjoint(frozenset(objects)):
return Response(status=204)
try:
related_instance_or_manager.remove(*serializer.validated_data)
except AttributeError:
raise Conflict(
'This object cannot be removed from this relationship without being '
'added to another'
)
else:
raise MethodNotAllowed('DELETE')
result_serializer = self._instantiate_serializer(related_instance_or_manager)
return Response(result_serializer.data)
示例4: get_uploader
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def get_uploader(cls, request):
# Process the request to identify if it's a standard upload request
# or a request that is related to a chunked upload. Return the right
# kind of uploader to handle this.
if request.method == 'PATCH':
return FilepondChunkedFileUploader()
if request.method == 'HEAD':
return FilepondChunkedFileUploader()
elif request.method == 'POST':
file_obj = cls._get_file_obj(request)
if (file_obj == '{}' and
request.META.get('HTTP_UPLOAD_LENGTH', None)):
LOG.debug('Returning CHUNKED uploader to handle '
'upload request... ')
return FilepondChunkedFileUploader()
else:
raise MethodNotAllowed('%s is an invalid method type'
% (request.method))
# If we didn't identify the need for a chunked uploader in any of the
# above tests, treat this as a standard upload
LOG.debug('Returning STANDARD uploader to handle upload request... ')
return FilepondStandardFileUploader()
示例5: get_required_permissions
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def get_required_permissions(self, method):
"""
Given a model and an HTTP method, return the list of permission
codes that the user is required to have.
:param method: str. e.g. Mostly keys of `perms_map`
:return:
"""
app_label = self.APP_LABEL
kwargs = {
'app_label': app_label,
'model_name': self.MODEL_NAME
}
try:
perm_list = self.perms_map[method]
except KeyError:
raise exceptions.MethodNotAllowed(method)
perms = [perm % kwargs for perm in perm_list]
# Because `ObjectPermissionMixin.get_perms()` returns codenames only, remove the
# `app_label` prefix before returning
return [perm.replace("{}.".format(app_label), "") for perm in perms]
示例6: perform_destroy
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def perform_destroy(self, instance):
# Only directly-applied permissions may be modified; forbid deleting
# permissions inherited from ancestors
if instance.inherited:
raise exceptions.MethodNotAllowed(
self.request.method,
detail='Cannot delete inherited permissions.'
)
# Make sure the requesting user has the share_ permission on
# the affected object
with transaction.atomic():
affected_object = instance.content_object
codename = instance.permission.codename
if not ObjectPermissionHelper.user_can_share(affected_object,
self.request.user,
codename):
raise exceptions.PermissionDenied()
instance.content_object.remove_perm(
instance.user,
instance.permission.codename
)
示例7: test_get_uploader_get_req
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def test_get_uploader_get_req(self):
self.request.method = 'GET'
with self.assertRaisesMessage(MethodNotAllowed,
'GET is an invalid method type'):
FilepondFileUploader.get_uploader(self.request)
示例8: raise_exception_treat
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def raise_exception_treat(func):
@functools.wraps(func)
def inner(self, request, *args, **kwargs):
try:
return func(self, request, *args, **kwargs)
except ValidationError, error:
log.error(error)
raise rest_exceptions.ValidationExceptionJson(error)
except (exceptions_api.APIException, exceptions_api.AuthenticationFailed,
exceptions_api.MethodNotAllowed, exceptions_api.NotAcceptable,
exceptions_api.NotAuthenticated, exceptions_api.ParseError,
exceptions_api.PermissionDenied, exceptions_api.Throttled,
exceptions_api.UnsupportedMediaType, rest_exceptions.ValidationAPIException), error:
log.error(error)
raise error
示例9: get_rule
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def get_rule(self, request, model_cls, method_map):
template = getattr(method_map, request.method)
if not template:
raise exceptions.MethodNotAllowed(request.method)
return template.format(
app_label=model_cls._meta.app_label,
model_name=model_cls._meta.model_name
)
示例10: has_permission
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def has_permission(self, request, view):
if not request.user:
return False
elif request.user.is_superuser:
return True
parent_object = self._get_parent_object(view)
user = request.user
if user.is_anonymous:
user = get_anonymous_user()
user_permissions = self._get_user_permissions(parent_object, user)
view_permissions = self.get_required_permissions("GET")
can_view = set(view_permissions).issubset(user_permissions)
try:
required_permissions = self.get_required_permissions(request.method)
except exceptions.MethodNotAllowed as e:
# Only reveal the HTTP 405 if the user has view access
if can_view:
raise e
else:
raise Http404
has_perm = set(required_permissions).issubset(user_permissions)
if has_perm:
# Access granted!
return True
if not has_perm and can_view:
# If users are allowed to view, we want to show them HTTP 403
return False
# Don't reveal the existence of this object to users who do not have
# permission to view it
raise Http404
示例11: get_required_permissions
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def get_required_permissions(self, method, model_cls):
"""
Given a model and an HTTP method, return the list of permission
codes that the user is required to have.
"""
kwargs = {
'app_label': model_cls._meta.app_label,
'model_name': model_cls._meta.model_name
}
if method not in self.perms_map:
raise exceptions.MethodNotAllowed(method)
return [perm % kwargs for perm in self.perms_map[method]]
示例12: get_required_object_permissions
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def get_required_object_permissions(self, method, model_cls):
kwargs = {
'app_label': model_cls._meta.app_label,
'model_name': model_cls._meta.model_name
}
if method not in self.perms_map:
raise exceptions.MethodNotAllowed(method)
return [perm % kwargs for perm in self.perms_map[method]]
示例13: http_method_not_allowed
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def http_method_not_allowed(self, request, *args, **kwargs):
"""
If `request.method` does not correspond to a handler method,
determine what kind of exception to raise.
"""
raise exceptions.MethodNotAllowed(request.method)
示例14: raise_json_validate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import MethodNotAllowed [as 别名]
def raise_json_validate(info=None):
def raise_json_validate_inner(func):
@wraps(func)
def inner(self, request, *args, **kwargs):
try:
return func(self, request, *args, **kwargs)
except ValidationError, error:
msg = list()
if error.flatten():
for pointer, reasons in error.flatten().items():
valor = resolve(
error[1], pointer) if pointer != '#/' else ''
msg.append({
'error_pointer': pointer,
'received_value': valor,
'error_reasons': list(reasons)
})
else:
msg.append({
'error_pointer': error[0],
'received_value': None,
'error_reasons': list(error[1])
})
res = {
'errors': msg
}
if info:
protocol = 'https' if request.is_secure() else 'http'
res['spec'] = '%s://%s/api/v3/help/%s/' % (
protocol, request.get_host(), info)
log.error(res)
raise rest_exceptions.ValidationExceptionJson(res)
except exceptions_api.AuthenticationFailed, error:
log.exception(error)
raise error
except exceptions_api.MethodNotAllowed, error:
log.exception(error)
raise error