Python rest_framework.status.HTTP_202_ACCEPTED Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_202_ACCEPTED(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: desec-stack   Author: desec-io   File: views.py    License: 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 2
Project: kobo-predict   Author: awemulya   File: labels_mixin.py    License: 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 3
Project: substra-backend   Author: SubstraFoundation   File: tests_query_objective.py    License: 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 4
Project: substra-backend   Author: SubstraFoundation   File: tests_query_algo.py    License: 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 5
Project: scale   Author: ngageoint   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def _cancel_v6(self, request, scan_id):
        """Cancels a scan job

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :param scan_id: The ID of the Scan process
        :type scan_id: int encoded as a str
        :returns: The HTTP response to send back to the user
        :rtype: :class:`rest_framework.response.Response`
        """

        canceled_ids = Scan.objects.cancel_scan(scan_id)

        resp_dict = {'id': scan_id, 'canceled_jobs': canceled_ids}
        return JsonResponse(resp_dict, status=status.HTTP_202_ACCEPTED)
        # return Response(resp_dict, status=status.HTTP_202_ACCEPTED)
        # return Response(JSONRenderer().render(canceled_ids), status=status.HTTP_202_ACCEPTED) 
Example 6
Project: scale   Author: ngageoint   File: test_views.py    License: Apache License 2.0 6 votes vote down vote up
def test_cancel_scan_job_nothing_to_cancel(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.job.status = "COMPLETED"
        self.scan.job.save()
        self.scan.save()
        self.ingest = ingest_test_utils.create_ingest(scan=self.scan, file_name='test3.txt',
                                                      status='QUEUED')
        self.ingest.job.status = "CANCELED"
        self.ingest.job.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']), 0)

        msg_create.assert_not_called()
        mock_msg_mgr.assert_not_called() 
Example 7
Project: scale   Author: ngageoint   File: test_views.py    License: Apache License 2.0 6 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 8
Project: scale   Author: ngageoint   File: test_views.py    License: 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 9
Project: scale   Author: ngageoint   File: views.py    License: 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 10
Project: scale   Author: ngageoint   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def queue_casino_recipes(self, request):
        """Creates and queues the specified number of Scale Casino recipes

        :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-casino', 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 11
Project: scale   Author: ngageoint   File: views.py    License: Apache License 2.0 6 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 12
Project: scale   Author: ngageoint   File: views.py    License: 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 13
Project: lego   Author: webkom   File: views.py    License: MIT License 6 votes vote down vote up
def send(self, request, *args, **kwargs):
        instance = self.get_object()

        if instance.sent:
            raise exceptions.ValidationError("message already sent")

        instance.send()

        track(
            request.user,
            "announcement.send",
            properties={"announcement_id": instance.id},
        )

        return Response(
            {"status": "message queued for sending"}, status=status.HTTP_202_ACCEPTED
        ) 
Example 14
Project: lego   Author: webkom   File: password_reset.py    License: MIT License 6 votes vote down vote up
def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        email = serializer.validated_data["email"]
        try:
            user = User.objects.get(email__iexact=email)
        except User.DoesNotExist:
            raise ValidationError({"email": "User with that email does not exist"})
        token = PasswordReset.generate_reset_token(email)
        send_email.delay(
            to_email=email,
            context={"name": user.full_name, "token": token},
            subject="Nullstill ditt passord på abakus.no",
            plain_template="users/email/reset_password.txt",
            html_template="users/email/reset_password.html",
            from_email=None,
        )

        return Response(status=status.HTTP_202_ACCEPTED) 
Example 15
Project: lego   Author: webkom   File: registration.py    License: MIT License 6 votes vote down vote up
def create(self, request, *args, **kwargs):
        """
        Attempts to create a registration token and email it to the user.
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email = serializer.validated_data.get("email")
        token = Registrations.generate_registration_token(email)

        send_email.delay(
            to_email=email,
            context={"token": token},
            subject="Velkommen til Abakus.no",
            plain_template="users/email/registration.txt",
            html_template="users/email/registration.html",
            from_email=None,
        )

        return Response(status=status.HTTP_202_ACCEPTED) 
Example 16
Project: lego   Author: webkom   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_with_auth(self, mock_verify_captcha, mock_send_message):
        self.client.force_authenticate(self.user)
        response = self.client.post(
            self.url,
            {
                "title": "title",
                "message": "message",
                "anonymous": True,
                "captcha_response": "test",
                "recipient_group": None,
            },
        )
        self.assertEquals(status.HTTP_202_ACCEPTED, response.status_code)
        mock_verify_captcha.assert_called_once()
        mock_send_message.assert_called_once_with(
            "title", "message", self.user, True, None
        ) 
Example 17
Project: lego   Author: webkom   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_committee_as_recipient(self, mock_verify_captcha, mock_send_message):
        webkom = AbakusGroup.objects.get(name="Webkom")
        webkom_id = webkom.id

        self.client.force_authenticate(self.user)

        response = self.client.post(
            self.url,
            {
                "title": "title",
                "message": "message",
                "anonymous": True,
                "captcha_response": "test",
                "recipient_group": webkom_id,
            },
        )
        self.assertEquals(status.HTTP_202_ACCEPTED, response.status_code)
        mock_verify_captcha.assert_called_once()
        mock_send_message.assert_called_once_with(
            "title", "message", self.user, True, webkom
        ) 
Example 18
Project: lego   Author: webkom   File: test_submissions_api.py    License: 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 19
Project: lego   Author: webkom   File: test_submissions_api.py    License: 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 20
Project: lego   Author: webkom   File: views.py    License: 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 21
Project: tfrs   Author: bcgov   File: Document.py    License: 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 22
Project: GloboNetworkAPI   Author: globocom   File: networkv6.py    License: 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
Project: GloboNetworkAPI   Author: globocom   File: networkv6.py    License: 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 24
Project: GloboNetworkAPI   Author: globocom   File: networkv6.py    License: 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 25
Project: GloboNetworkAPI   Author: globocom   File: networkv6.py    License: 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 26
Project: GloboNetworkAPI   Author: globocom   File: networkv6.py    License: 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 27
Project: GloboNetworkAPI   Author: globocom   File: networkv4.py    License: 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 28
Project: GloboNetworkAPI   Author: globocom   File: networkv4.py    License: 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 29
Project: GloboNetworkAPI   Author: globocom   File: networkv4.py    License: 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 30
Project: GloboNetworkAPI   Author: globocom   File: networkv4.py    License: 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)