def update(self, instance, validated_data): raise exceptions.MethodNotAllowed('UPDATE')
def partial_update(self, request, pk=None): raise exceptions.MethodNotAllowed('PARTIAL UPDATE')
def deployment(self, request, uid): ''' A GET request retrieves the existing deployment, if any. A POST request creates a new deployment, but only if a deployment does not exist already. A PATCH request updates the `active` field of the existing deployment. A PUT request overwrites the entire deployment, including the form contents, but does not change the deployment's identifier ''' asset = self.get_object() # TODO: Require the client to provide a fully-qualified identifier, # otherwise provide less kludgy solution if 'identifier' not in request.data and 'id_string' in request.data: id_string = request.data.pop('id_string')[0] backend_name = request.data['backend'] try: backend = DEPLOYMENT_BACKENDS[backend_name] except KeyError: raise KeyError( 'cannot retrieve asset backend: "{}"'.format(backend_name)) request.data['identifier'] = backend.make_identifier( request.user.username, id_string) if request.method == 'GET': if not asset.has_deployment: raise Http404 else: serializer = DeploymentSerializer( asset.deployment, context=self.get_serializer_context()) # TODO: Understand why this 404s when `serializer.data` is not # coerced to a dict return Response(dict(serializer.data)) elif request.method == 'POST': if not asset.can_be_deployed: raise BadAssetTypeException( "Only surveys may be deployed, but this asset is a {}". format(self.asset_type)) else: if asset.has_deployment: raise exceptions.MethodNotAllowed( method=request.method, detail='Use PATCH to update an existing deployment') serializer = DeploymentSerializer(data=request.data, context={'asset': asset}) serializer.is_valid(raise_exception=True) serializer.save() # TODO: Understand why this 404s when `serializer.data` is not # coerced to a dict return Response(dict(serializer.data)) elif request.method == 'PATCH': if not asset.can_be_deployed: raise BadAssetTypeException( "Only surveys may be deployed, but this asset is a {}". format(self.asset_type)) else: if not asset.has_deployment: raise exceptions.MethodNotAllowed( method=request.method, detail='Use POST to create a new deployment') serializer = DeploymentSerializer(asset.deployment, data=request.data, context={'asset': asset}, partial=True) serializer.is_valid(raise_exception=True) serializer.save() # TODO: Understand why this 404s when `serializer.data` is not # coerced to a dict return Response(dict(serializer.data))
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)
def destroy(self, request, pk=None): # disable this function raise exceptions.MethodNotAllowed('DESTROY')
def perform_create(self, serializer): request_user = self.request.user q = MachineRequest.objects.filter( (Q(created_by__id=request_user.id) & Q(instance_id=serializer.validated_data['instance'].id) & ~Q(status__name="failed") & ~Q(status__name="denied") & ~Q(status__name="completed") & ~Q(status__name="closed"))) if len(q) > 0: message = "Only one active request is allowed per provider." raise rest_exceptions.MethodNotAllowed('create', detail=message) # NOTE: An identity could possible have multiple memberships # It may be better to directly take membership rather than an identity identity_id = serializer.initial_data.get("identity") parent_machine = serializer.validated_data['instance'].provider_machine access_list = serializer.initial_data.get("access_list") or [] visibility = serializer.initial_data.get("new_application_visibility") new_provider = self._get_new_provider() if visibility in ["select", "private"]: share_with_admins(access_list, parent_machine.provider.uuid) share_with_self(access_list, request_user.username) access_list = remove_duplicate_users(access_list) status, _ = StatusType.objects.get_or_create(name="pending") new_machine_provider = Provider.objects.filter(id=new_provider.id) new_machine_owner = AtmosphereUser.objects.filter(id=request_user.id) parent_machine = ProviderMachine.objects.filter(id=parent_machine.id) if new_machine_provider.count(): new_machine_provider = new_machine_provider[0] else: raise rest_exceptions.ParseError( detail="Could not retrieve new machine provider.") if new_machine_owner.count(): new_machine_owner = new_machine_owner[0] else: raise rest_exceptions.ParseError( detail="Could not retrieve new machine owner.") if parent_machine.count(): parent_machine = parent_machine[0] else: raise rest_exceptions.ParseError( detail="Could not retrieve parent machine.") new_tags = self.filter_tags( request_user, serializer.validated_data.get("new_version_tags", "")) try: membership = IdentityMembership.objects.get(identity=identity_id) instance = serializer.save( membership=membership, status=status, created_by=request_user, new_machine_provider=new_provider, new_machine_owner=request_user, new_version_tags=new_tags, access_list=access_list, old_status= "pending", # TODO: Is this required or will it default to pending? parent_machine=parent_machine) instance.migrate_access_to_membership_list(access_list) self.submit_action(instance) except (core_exceptions.ProviderLimitExceeded, core_exceptions.RequestLimitExceeded): message = "Only one active request is allowed per provider." raise rest_exceptions.MethodNotAllowed('create', detail=message) except core_exceptions.InvalidMembership: message = ("The user '%s' is not a valid member." % request_user.username) raise rest_exceptions.ParseError(detail=message) except IdentityMembership.DoesNotExist: message = ("The identity '%s' does not have a membership" % identity_id) raise rest_exceptions.ParseError(detail=message) except Exception as e: message = { "An error was encoutered when submitting the request: %s" % e.message } logger.exception(e) raise rest_exceptions.ParseError(detail=message)
def partial_update(self, request, *args, **kwargs): raise exceptions.MethodNotAllowed('PATCH')
def get_required_permissions(self, method, app_label, perms_map): if method not in perms_map: raise exceptions.MethodNotAllowed(method) return [perm.format(app_label) for perm in perms_map[method]]
def create(self, validated_data): raise exceptions.MethodNotAllowed( 'Instances creating is not allowed here')
def authenticate(self, request): if "Authorization" in request.headers: return self.authenticate_token(request.headers["Authorization"]) if request.method != "GET": return self.authenticate_credentials(request) raise exceptions.MethodNotAllowed(method=request.method)
def has_permission(self, request, view): if view.kwargs: if request.method == "DELETE": return True raise exceptions.MethodNotAllowed(request.method) return True
def check_method(cls, request: HttpRequest) -> bool: if request.method not in cls.ALLOWED_METHODS: raise exceptions.MethodNotAllowed(method=request.method)
def sub_perform_update(self, serializer): t_type = self.shift_data.get('type', int) # 同意申请,邀请 if int(t_type) == 1: team_user = self.get_object() if team_user.user.team is not None: serializer.save( status=TeamUserStatus.EXIT, has_handle=True, modify_time=timezone.now(), team_leader=False ) raise exceptions.NotAcceptable(ResError.USER_HAVE_TEAM) with transaction.atomic(): teamuser = serializer.save( status=TeamUserStatus.JOIN, has_handle=True, modify_time=timezone.now(), team_leader=False ) user = teamuser.user user.team = teamuser.team user.save() # 调用系统通知 content = ugettext("x_wel_join") + user.team.name add_sys_notice(user=self.request.user, name=ugettext("x_team_notice"), content=content, group=SysNotice.Group.SELECT, notified_person=teamuser.user, type=SysNotice.Type.TEAMMESSAGE, ) # 拒绝申请 if int(t_type) == 2: with transaction.atomic(): teamuser = serializer.save( status=TeamUserStatus.REFUSE, has_handle=True, modify_time=timezone.now(), ) if self.request.user == teamuser.user: teamleader = TeamUser.objects.filter(team_id=teamuser.team, team_leader=True).first() teamUserNotice = TeamUserNotice.objects.create( user=teamleader.user, has_notice=False, content=teamuser.user.username + ugettext("x_refused_invite"), create_time=timezone.now(), modify_time=timezone.now() ) content = teamuser.user.first_name + ugettext("x_refused_invite") notified_person=teamleader.user else: teamUserNotice = TeamUserNotice.objects.create( user=teamuser.user, has_notice=False, content=teamuser.team.name + ugettext("x_clan_refuse_apply"), create_time=timezone.now(), modify_time=timezone.now() ) content = teamuser.team.name + ugettext("x_clan_refuse_apply") notified_person = teamuser.user teamUserNotice.save() add_sys_notice(user=self.request.user, name=ugettext("x_team_notice"), content=content, group=SysNotice.Group.SELECT, notified_person=notified_person, type=SysNotice.Type.TEAMMESSAGE, ) # 退出队伍 if int(t_type) == 3: teamuser = serializer.save(status=TeamUserStatus.EXIT, modify_time=timezone.now()) user = teamuser.user team = user.team user.team = None user.save() team_leader = TeamUser.objects.filter(team=team, team_leader=True).first().user add_sys_notice(user=self.request.user, name=ugettext("x_team_notice"), content=user.first_name + ugettext("x_quit_team"), group=SysNotice.Group.SELECT, notified_person=team_leader, type=SysNotice.Type.TEAMMESSAGE, ) # 移交队长 if int(t_type) == 4: if not self.request.user.team: raise exceptions.MethodNotAllowed(ResError.METHODNOTALLOWED) if TeamUser.objects.filter(user=self.request.user, team=self.request.user.team, status=TeamUserStatus.JOIN).first().team_leader: raise exceptions.MethodNotAllowed(ResError.METHODNOTALLOWED) with transaction.atomic(): teamleader = TeamUser.objects.filter(user=self.request.user, team=self.request.user.team, status=TeamUserStatus.JOIN).first() teamleader.team_leader = False teamleader.save() teamuser = serializer.save(team_leader=True, modify_time=timezone.now()) teamUserNotice = TeamUserNotice.objects.create( user=teamuser.user, has_notice=False, content=u"你已成为" + teamuser.team.name + u"的队长", create_time=timezone.now(), modify_time=timezone.now(), ) teamUserNotice.save() add_sys_notice(user=self.request.user, name=ugettext("x_team_notice"), content=u"你已成为" + teamuser.team.name + u"的队长", group=SysNotice.Group.SELECT, notified_person=teamuser.user, type=SysNotice.Type.TEAMMESSAGE, ) # 踢出队伍 if int(t_type) == 6: if not self.request.user.team: raise exceptions.MethodNotAllowed(ResError.METHODNOTALLOWED) if not TeamUser.objects.filter(user=self.request.user, team=self.request.user.team, status=TeamUserStatus.JOIN).first().team_leader: raise exceptions.MethodNotAllowed(ResError.METHODNOTALLOWED) with transaction.atomic(): team_user = serializer.save(status=TeamUserStatus.DELETE, modify_time=timezone.now()) user = team_user.user user.team = None teamUserNotice = TeamUserNotice.objects.create( user=team_user.user, has_notice=False, content=team_user.team.name + ugettext(u'战队将你踢出!'), create_time=timezone.now(), modify_time=timezone.now(), ) teamUserNotice.save() user.save() add_sys_notice(user=self.request.user, name=ugettext("x_team_notice"), content=team_user.team.name + ugettext(u'战队将你踢出!'), group=SysNotice.Group.SELECT, notified_person=team_user.user, type=SysNotice.Type.TEAMMESSAGE, ) return True
def get_serializer_class(self): if self.request.method == 'POST': return CreateBudgetSerializer elif self.request.method == 'GET': return ListBudgetSerialiser raise exceptions.MethodNotAllowed(self.request.method)
def perform_update(self, serializer): # TODO: not supported for Helm. Will be supported for # SheetHelm. raise exceptions.MethodNotAllowed("Update not supported yet")
def dispatch(self, request): view_class = self._route.get(request.method) if not view_class: raise exceptions.MethodNotAllowed(request.method) return view_class
def perform_update(self, serializer): # Update should not be allowed for sheet or effect fields, but just # the changeable fields. raise exceptions.MethodNotAllowed("Update not supported yet")
def get(self, *args, **kwargs): """GET revoke token Logouts using GET are no longer supported """ raise exceptions.MethodNotAllowed("GET")
def list(self, request, *args, **kwargs): raise exceptions.MethodNotAllowed(request.method)
def http_method_not_allowed(self, request, *args, **kwargs): """ Called if `request.method` does not corrospond to a handler method. """ raise exceptions.MethodNotAllowed(request.method)
class MethodNotAllowedView(BaseErrorView): exception = exceptions.MethodNotAllowed("GET")
def test_method_not_allowed_allows_dict_detail(self): exc = drf_exceptions.MethodNotAllowed(u'POST', {u'error_code': -1}) assert exc.detail == {u'error_code': u'-1'}
def create(self, request): # disable this function raise exceptions.MethodNotAllowed('CREATE')
def delete(self, request, team_id, pk): if get_object_or_404(TeamMember, pk=pk).user == request.user: # Don't allow a team member to delete themselves raise exceptions.MethodNotAllowed( "Own team membership cannot be deleted.") return super().delete(self, request, team_id, pk)
def update(self, request, *args, **kwargs): raise exceptions.MethodNotAllowed('UPDATE')
def update(self, request, *args, **kwargs): partial = kwargs.get('partial', False) if not partial: # PUT are not supported, only PATCH is. raise exceptions.MethodNotAllowed(request.method) return super(ExtensionViewSet, self).update(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs): raise exceptions.MethodNotAllowed('GET')
def update(self, instance, validated_data): raise exceptions.MethodNotAllowed( method=self.context['request'].method)
def get_required_permissions(self, method, model_cls): if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return self.perms_map[method]
def create(self, validated_data): raise exceptions.MethodNotAllowed('POST')