Python rest_framework.status.HTTP_202_ACCEPTED Examples

The following are 30 code examples of rest_framework.status.HTTP_202_ACCEPTED(). 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.status , or try the search function .
Example #1
Source File: views.py    From scale with Apache License 2.0 7 votes vote down vote up
def queue_hello_jobs(self, request):
        """Creates and queues the specified number of Scale Hello jobs

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        num = rest_util.parse_int(request, 'num')

        if num < 1:
            raise BadParameter('num must be at least 1')

        # TODO: in the future, send command message to do this asynchronously
        try:
            recipe_type = RecipeType.objects.get(name='scale-hello', revision_num='1')
            for _ in xrange(num):
                Queue.objects.queue_new_recipe_for_user_v6(recipe_type, Data())
        except (InvalidData, InvalidRecipeData, InactiveRecipeType) as ex:
            message = 'Unable to create new recipe'
            logger.exception(message)
            raise BadParameter('%s: %s' % (message, unicode(ex)))

        return Response(status=status.HTTP_202_ACCEPTED) 
Example #2
Source File: test_views.py    From scale with Apache License 2.0 7 votes vote down vote up
def test_cancel_scan_broken_ingest_job(self, msg_create, mock_msg_mgr):
        """Tests no cancel messages generated when jobs are not in a cancelable state"""

        self.scan.job = job_utils.create_job()
        self.scan.save()
        self.ingest = ingest_test_utils.create_ingest(scan=self.scan, file_name='test3.txt',
                                                      status='QUEUED')
        self.ingest.job = None
        self.ingest.save()

        url = '/%s/scans/cancel/%d/' % (self.api, self.scan.id)
        response = self.client.generic('POST', url, json.dumps({'ingest': True}), 'application/json')
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
        
        result = json.loads(response.content)
        self.assertEqual(result['id'], unicode(self.scan.id))
        self.assertEqual(len(result['canceled_jobs']), 1)

        msg_create.assert_called()
        mock_msg_mgr.assert_called() 
Example #3
Source File: networkv4.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def put(self, request, *args, **kwargs):
        """Edit NetworkV4."""

        response = list()
        nets = request.DATA
        json_validate(SPECS.get('networkv4_put')).validate(nets)

        user = request.user

        for net in nets['networks']:
            task_obj = tasks.update_networkv4.apply_async(args=[net, user.id],
                                                          queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #4
Source File: networkv4.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Delete NetworkV4."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user

        for obj_id in obj_ids:
            task_obj = tasks.delete_networkv4.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #5
Source File: networkv4.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Undeploy NetworkV4."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user

        for obj_id in obj_ids:
            task_obj = tasks.undeploy_networkv4.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #6
Source File: labels_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _labels_delete(label, instance):
    """Delete a label from an instance.

    :param instance: object to delete label from.
    :param label: the label to delete.

    :returns the status and all the tags.
    """
    count = instance.tags.count()
    instance.tags.remove(label)

    if isinstance(instance, XForm):
        xform_tags_delete.send(sender=XForm, xform=instance, tag=label)

    # Accepted, label does not exist hence nothing removed
    http_status = status.HTTP_202_ACCEPTED if count == instance.tags.count()\
        else status.HTTP_200_OK

    return [http_status, list(instance.tags.names())] 
Example #7
Source File: networkv4.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Deploy NetworkV4."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user

        for obj_id in obj_ids:
            task_obj = tasks.deploy_networkv4.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #8
Source File: networkv6.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Undeploy NetworkV6."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user.id

        for obj_id in obj_ids:
            task_obj = tasks.undeploy_networkv6.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #9
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):

        response = list()
        vip_ids = kwargs.get('obj_ids').split(',')
        user = request.user

        for vip_id in vip_ids:
            task_obj = tasks.vip_deploy.apply_async(args=[vip_id, user.id],
                                                    queue='napi.vip')

            task = {
                'id': vip_id,
                'task_id': task_obj.id
            }

        response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #10
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def put(self, request, *args, **kwargs):

        response = list()
        vips = request.DATA
        user = request.user
        json_validate(SPECS.get('vip_request_put')).validate(vips)
        verify_ports_vip(vips)

        for vip in vips.get('vips'):
            task_obj = tasks.vip_redeploy.apply_async(args=[vip, user.id],
                                                      queue='napi.vip')

            task = {
                'id': vip.get('id'),
                'task_id': task_obj.id
            }

        response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #11
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):

        response = list()
        pool_ids = kwargs['obj_ids'].split(';')
        user = request.user

        for pool_id in pool_ids:
            task_obj = tasks.pool_deploy.apply_async(args=[pool_id, user.id],
                                                     queue='napi.vip')

            task = {
                'id': pool_id,
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #12
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):

        response = list()
        pool_ids = kwargs.get('obj_ids').split(';')
        user = request.user

        for pool_id in pool_ids:
            task_obj = tasks.pool_undeploy.apply_async(args=[pool_id, user.id],
                                                       queue='napi.vip')

            task = {
                'id': pool_id,
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #13
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def put(self, request, *args, **kwargs):

        response = list()

        pools = request.DATA
        user = request.user
        json_validate(SPECS.get('pool_put')).validate(pools)
        verify_ports(pools)

        for pool in pools.get('server_pools'):
            task_obj = tasks.pool_redeploy.apply_async(args=[pool, user.id],
                                                       queue='napi.vip')

            task = {
                'id': pool.get('id'),
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #14
Source File: views.py    From desec-stack with MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        # Check password and extract email
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        new_email = serializer.validated_data['new_email']

        action = models.AuthenticatedChangeEmailUserAction(user=request.user, new_email=new_email)
        verification_code = serializers.AuthenticatedChangeEmailUserActionSerializer(action).data['code']
        request.user.send_email('change-email', recipient=new_email, context={
            'confirmation_link': reverse('confirm-change-email', request=request, args=[verification_code]),
            'old_email': request.user.email,
            'new_email': new_email,
        })

        # At this point, we know that we are talking to the user, so we can tell that we sent an email.
        return Response(data={'detail': 'Please check your mailbox to confirm email address change.'},
                        status=status.HTTP_202_ACCEPTED) 
Example #15
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Creates list of vlans."""

        response = list()
        data = request.DATA
        json_validate(SPECS.get('vlan_post')).validate(data)

        user = request.user

        for vlan in data['vlans']:
            task_obj = tasks.create_vlan.apply_async(args=[vlan, user.id],
                                                     queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #16
Source File: v3.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Deletes list of vlans."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user

        for obj_id in obj_ids:
            task_obj = tasks.delete_vlan.apply_async(args=[obj_id, user.id],
                                                     queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #17
Source File: networkv6.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Delete NetworkV6."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user

        for obj_id in obj_ids:
            task_obj = tasks.delete_networkv6.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #18
Source File: tests_query_objective.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def test_add_objective_no_sync_ok(self):
        self.add_default_data_manager()
        pkhash, data = self.get_default_objective_data()

        url = reverse('substrapp:objective-list')
        extra = {
            'HTTP_ACCEPT': 'application/json;version=0.0',
        }
        with mock.patch('substrapp.ledger.invoke_ledger') as minvoke_ledger:
            minvoke_ledger.return_value = {
                'message': 'Objective added in local db waiting for validation.'
                           'The substra network has been notified for adding this Objective'
            }
            response = self.client.post(url, data, format='multipart', **extra)

            r = response.json()

            self.assertEqual(r['pkhash'], pkhash)
            self.assertEqual(r['validated'], False)
            self.assertEqual(r['description'],
                             f'http://testserver/media/objectives/{r["pkhash"]}/{self.objective_description_filename}')
            self.assertEqual(r['metrics'],
                             f'http://testserver/media/objectives/{r["pkhash"]}/{self.objective_metrics_filename}')
            self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) 
Example #19
Source File: tests_query_algo.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def test_add_algo_no_sync_ok(self):
        self.add_default_objective()
        pkhash, data = self.get_default_algo_data()

        url = reverse('substrapp:algo-list')
        extra = {
            'HTTP_ACCEPT': 'application/json;version=0.0',
        }
        with mock.patch('substrapp.ledger.invoke_ledger') as minvoke_ledger:
            minvoke_ledger.return_value = {
                'message': 'Algo added in local db waiting for validation.'
                           'The substra network has been notified for adding this Algo'
            }
            response = self.client.post(url, data, format='multipart', **extra)
            r = response.json()

            self.assertEqual(r['pkhash'], pkhash)
            self.assertEqual(r['validated'], False)
            self.assertEqual(r['description'],
                             f'http://testserver/media/algos/{r["pkhash"]}/{self.data_description_filename}')
            self.assertEqual(r['file'],
                             f'http://testserver/media/algos/{r["pkhash"]}/{self.algo_filename}')
            self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) 
Example #20
Source File: networkv6.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Deploy NetworkV6."""

        response = list()
        obj_ids = kwargs['obj_ids'].split(';')

        user = request.user.id

        for obj_id in obj_ids:
            task_obj = tasks.deploy_networkv6.apply_async(
                args=[obj_id, user.id], queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #21
Source File: networkv6.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def put(self, request, *args, **kwargs):
        """Edit NetworkV6."""

        response = list()
        nets = request.DATA
        json_validate(SPECS.get('networkv6_put')).validate(nets)

        user = request.user

        for net in nets['networks']:
            task_obj = tasks.update_networkv6.apply_async(args=[net, user.id],
                                                          queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #22
Source File: networkv6.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Create NetworkV6."""

        response = list()
        nets = request.DATA
        json_validate(SPECS.get('networkv6_post')).validate(nets)

        user = request.user

        for net in nets['networks']:
            task_obj = tasks.create_networkv6.apply_async(args=[net, user.id],
                                                          queue='napi.network')

            task = {
                'task_id': task_obj.id
            }

            response.append(task)

        return Response(response, status=status.HTTP_202_ACCEPTED) 
Example #23
Source File: Document.py    From tfrs with Apache License 2.0 6 votes vote down vote up
def unlink(self, request, pk=None):
        """
        Unlink a credit trade from this document
        """
        document = self.get_object()

        serializer = CreditTradeLinkSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        credit_trade = serializer.validated_data['credit_trade']

        result = DocumentCreditTrade.objects.filter(credit_trade=credit_trade,
                                                    document=document)

        if not result.exists():
            return Response(None, status=status.HTTP_400_BAD_REQUEST)

        result.first().delete()

        return Response(None, status=status.HTTP_202_ACCEPTED) 
Example #24
Source File: views.py    From lego with MIT License 6 votes vote down vote up
def payment(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        event_id = self.kwargs.get("pk", None)
        event = Event.objects.get(id=event_id)
        registration = event.get_registration(request.user)

        if not event.is_priced or not event.use_stripe:
            raise PermissionDenied()

        if registration.has_paid():
            raise APIPaymentExists()
        registration.charge_status = constants.PAYMENT_PENDING
        registration.save()
        chain(
            async_payment.s(registration.id, serializer.data["token"]),
            registration_payment_save.s(registration.id),
        ).delay()
        payment_serializer = RegistrationPaymentReadSerializer(
            registration, context={"request": request}
        )
        return Response(data=payment_serializer.data, status=status.HTTP_202_ACCEPTED) 
Example #25
Source File: test_views.py    From scale with Apache License 2.0 6 votes vote down vote up
def test_all_jobs(self, mock_mgr):
        """Tests reprocessing all jobs in an existing recipe"""

        mock_mgr.return_value = MockCommandMessageManager()

        json_data = {
            'forced_nodes': {
                'all': True
            }
        }

        url = '/%s/recipes/%i/reprocess/' % (self.api, self.recipe1.id)
        response = self.client.generic('POST', url, json.dumps(json_data), 'application/json')
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED, response.content)

        new_recipe = Recipe.objects.get(superseded_recipe_id=self.recipe1.id)
        self.assertEqual(new_recipe.configuration['output_workspaces']['default'], self.workspace.name) 
Example #26
Source File: test_submissions_api.py    From lego with MIT License 6 votes vote down vote up
def test_hide_admin(self):
        """Calling the hide() endpoint should successfully set hide_from_public"""
        self.client.force_authenticate(user=self.admin_user)
        answer_pk = 3
        submission = Submission.objects.get(pk=1)
        answer = submission.answers.get(pk=answer_pk)
        self.assertFalse(answer.hide_from_public)

        response = self.client.post(
            _get_detail_url(1, 1) + "hide/?answer=" + str(answer_pk)
        )
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        response = self.client.get(_get_detail_url(1, 1))
        self.assertTrue(response.json())
        response_answers = response.json()["answers"]
        answer = next(x for x in response_answers if x["id"] == answer_pk)
        self.assertTrue("hideFromPublic" in answer)
        self.assertTrue(answer["hideFromPublic"]) 
Example #27
Source File: views.py    From scale with Apache License 2.0 6 votes vote down vote up
def queue_count_jobs(self, request):
        """Creates and queues the specified number of Scale Count jobs

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        num = rest_util.parse_int(request, 'num')

        if num < 1:
            raise BadParameter('num must be at least 1')

        # TODO: in the future, send command message to do this asynchronously
        try:
            recipe_type = RecipeType.objects.get(name='scale-count', revision_num='1')
            for _ in xrange(num):
                Queue.objects.queue_new_recipe_for_user_v6(recipe_type, Data())
        except (InvalidData, InvalidRecipeData, InactiveRecipeType) as ex:
            message = 'Unable to create new recipe'
            logger.exception(message)
            raise BadParameter('%s: %s' % (message, unicode(ex)))

        return Response(status=status.HTTP_202_ACCEPTED) 
Example #28
Source File: views.py    From scale with Apache License 2.0 6 votes vote down vote up
def queue_bake_jobs(self, request):
        """Creates and queues the specified number of Scale Bake jobs

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        num = rest_util.parse_int(request, 'num')

        if num < 1:
            raise BadParameter('num must be at least 1')

        # TODO: in the future, send command message to do this asynchronously
        try:
            recipe_type = RecipeType.objects.get(name='scale-bake', revision_num='1')
            for _ in xrange(num):
                Queue.objects.queue_new_recipe_for_user_v6(recipe_type, Data())
        except (InvalidData, InvalidRecipeData, InactiveRecipeType) as ex:
            message = 'Unable to create new recipe'
            logger.exception(message)
            raise BadParameter('%s: %s' % (message, unicode(ex)))

        return Response(status=status.HTTP_202_ACCEPTED) 
Example #29
Source File: test_submissions_api.py    From lego with MIT License 6 votes vote down vote up
def test_show_admin(self):
        """Calling the show() endpoint should successfully set hide_from_public"""
        self.client.force_authenticate(user=self.admin_user)
        answer_pk = 3
        submission = Submission.objects.get(pk=1)
        answer = submission.answers.get(pk=answer_pk)
        answer.hide()

        response = self.client.post(
            _get_detail_url(1, 1) + "show/?answer=" + str(answer_pk)
        )
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        response = self.client.get(_get_detail_url(1, 1))
        self.assertTrue(response.json())
        response_answers = response.json()["answers"]
        answer = next(x for x in response_answers if x["id"] == answer_pk)
        self.assertTrue("hideFromPublic" in answer)
        self.assertFalse(answer["hideFromPublic"]) 
Example #30
Source File: views.py    From lego with MIT License 5 votes vote down vote up
def create(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        title = serializer.validated_data["title"]
        message = serializer.validated_data["message"]
        anonymous = serializer.validated_data["anonymous"]
        recipient_group = serializer.validated_data["recipient_group"]

        send_message(title, message, request.user, anonymous, recipient_group)

        if recipient_group:
            serializer.validated_data["recipient_group"] = recipient_group.id

        return Response(serializer.validated_data, status=status.HTTP_202_ACCEPTED)