Python rest_framework.exceptions.MethodNotAllowed() Examples
The following are 15
code examples of rest_framework.exceptions.MethodNotAllowed().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.exceptions
, or try the search function
.
Example #1
Source File: consumers.py From djangochannelsrestframework with MIT License | 6 votes |
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)
Example #2
Source File: consumers.py From djangochannelsrestframework with MIT License | 6 votes |
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.actions: raise MethodNotAllowed(method=action) content, status = await self.call_view(action=action, **kwargs) await self.reply( action=action, request_id=request_id, data=content, status=status ) except Exception as exc: await self.handle_exception(exc, action=action, request_id=request_id)
Example #3
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #4
Source File: views.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #5
Source File: uploaders.py From django-drf-filepond with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example #6
Source File: permissions.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
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]
Example #7
Source File: object_permission.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
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 )
Example #8
Source File: test_uploaders_base.py From django-drf-filepond with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #9
Source File: decorators.py From GloboNetworkAPI with Apache License 2.0 | 5 votes |
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
Example #10
Source File: permissions.py From adhocracy4 with GNU Affero General Public License v3.0 | 5 votes |
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 )
Example #11
Source File: permissions.py From kpi with GNU Affero General Public License v3.0 | 5 votes |
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
Example #12
Source File: permissions.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
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]]
Example #13
Source File: permissions.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
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]]
Example #14
Source File: views.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
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)
Example #15
Source File: json_validate.py From GloboNetworkAPI with Apache License 2.0 | 4 votes |
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