Python rest_framework.status.HTTP_409_CONFLICT Examples

The following are 30 code examples of rest_framework.status.HTTP_409_CONFLICT(). 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: api_views.py    From swarfarm with Apache License 2.0 6 votes vote down vote up
def create(self, request, *args, **kwargs):
        errors = []
        validation_failures = []

        schema_errors, validation_errors = validate_sw_json(request.data, request.user.summoner)

        if schema_errors:
            errors.append(schema_errors)

        if validation_errors:
            validation_failures = "Uploaded data does not match previously imported data. To override, set import preferences to ignore validation errors and import again."

        import_options = request.user.summoner.preferences.get('import_options', self.default_import_options)

        if not errors and (not validation_failures or import_options['ignore_validation_errors']):
            # Queue the import
            task = com2us_data_import.delay(request.data, request.user.summoner.pk, import_options)
            return Response({'job_id': task.task_id})

        elif validation_failures:
            return Response({'validation_error': validation_failures}, status=status.HTTP_409_CONFLICT)
        else:
            return Response({'error': errors}, status=status.HTTP_400_BAD_REQUEST) 
Example #2
Source File: views.py    From micromasters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Create a new channel"""
        serializer = ChannelSerializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        try:
            serializer.save()
        except ChannelAlreadyExistsException:
            return Response(
                {"name": "A channel with that name already exists"},
                status=status.HTTP_409_CONFLICT,
            )

        return Response(
            serializer.data,
            status=status.HTTP_201_CREATED,
        ) 
Example #3
Source File: views_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_create_channel_duplicate(mocker, patched_users_api):
    """creating a duplicate channel should return an error"""
    client = APIClient()
    role = RoleFactory.create(role=Staff.ROLE_ID)
    role.user.is_superuser = True
    role.user.save()
    client.force_login(role.user)

    channel = ChannelFactory.create()
    mocker.patch(
        'discussions.serializers.add_channel',
        side_effect=ChannelAlreadyExistsException,
        autospec=True,
    )

    create_channel_input = _make_create_channel_input(role.program.id, 'description')
    resp = client.post(reverse('channel-list'), data={
        **create_channel_input,
        "name": channel.name,
    }, format="json")
    assert resp.status_code == statuses.HTTP_409_CONFLICT
    assert resp.json() == {"name": "A channel with that name already exists"} 
Example #4
Source File: algo.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def _create(self, request, file):
        try:
            pkhash = get_hash(file)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            raise ValidationException(e.args, '(not computed)', st)

        serializer = self.get_serializer(data={
            'pkhash': pkhash,
            'file': file,
            'description': request.data.get('description')
        })

        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            if find_primary_key_error(e):
                st = status.HTTP_409_CONFLICT
            raise ValidationException(e.args, pkhash, st)
        else:
            # create on ledger + db
            return self.commit(serializer, request) 
Example #5
Source File: datamanager.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def _create(self, request, data_opener):

        try:
            pkhash = get_hash(data_opener)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            raise ValidationException(e.args, '(not computed)', st)

        serializer = self.get_serializer(data={
            'pkhash': pkhash,
            'data_opener': data_opener,
            'description': request.data.get('description'),
            'name': request.data.get('name'),
        })

        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            if find_primary_key_error(e):
                st = status.HTTP_409_CONFLICT
            raise ValidationException(e.args, pkhash, st)
        else:
            # create on ledger + db
            return self.commit(serializer, request) 
Example #6
Source File: test_views.py    From drf-tus with MIT License 6 votes vote down vote up
def test_terminate_while_saving(self):
        # Create upload
        upload = UploadFactory(
            filename='test_data.txt', upload_metadata=json.dumps({'filename': 'test_data.txt'}), upload_length=100,
            state=states.SAVING)

        # Prepare headers
        headers = {
            'Tus-Resumable': tus_api_version,
        }

        # Perform request
        result = self.client.delete(
            reverse('rest_framework_tus:api:upload-detail', kwargs={'guid': upload.guid}), headers=headers)

        # Check result
        assert result.status_code == status.HTTP_409_CONFLICT

        # Verify existence
        assert get_upload_model().objects.filter(guid=upload.guid).exists() 
Example #7
Source File: compositealgo.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def _create(self, request, file):

        pkhash = get_hash(file)
        serializer = self.get_serializer(data={
            'pkhash': pkhash,
            'file': file,
            'description': request.data.get('description')
        })

        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            if find_primary_key_error(e):
                st = status.HTTP_409_CONFLICT
            raise ValidationException(e.args, pkhash, st)
        else:
            # create on ledger + db
            return self.commit(serializer, request) 
Example #8
Source File: tests_query_datasample.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def test_add_data_sample_ko_already_exists(self):
        url = reverse('substrapp:data_sample-list')

        self.add_default_data_manager()

        file_mock = MagicMock(spec=InMemoryUploadedFile)
        file_mock.name = 'foo.zip'
        file_mock.read = MagicMock(return_value=self.data_file.file.read())
        file_mock.open = MagicMock(return_value=file_mock)

        _, datasamples_path_from_file = store_datasamples_archive(file_mock)

        d = DataSample(path=datasamples_path_from_file)
        # trigger pre save
        d.save()

        data = {
            'file': file_mock,
            'json': json.dumps({
                'data_manager_keys': [get_hash(self.data_data_opener)],
                'test_only': True,
            })
        }
        extra = {
            'HTTP_ACCEPT': 'application/json;version=0.0',
        }

        with mock.patch.object(zipfile, 'is_zipfile') as mis_zipfile:
            mis_zipfile.return_value = True
            response = self.client.post(url, data, format='multipart', **extra)
            r = response.json()
            self.assertEqual(r['message'],
                             [[{'pkhash': ['data sample with this pkhash already exists.']}]])
            self.assertEqual(response.status_code, status.HTTP_409_CONFLICT) 
Example #9
Source File: views.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def enable(self, request, pk=None):
        recipe = self.get_object()

        if recipe.approved_revision:
            try:
                recipe.approved_revision.enable(user=request.user)
            except EnabledState.NotActionable as e:
                return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT)
        else:
            return Response(
                {"error": "Cannot enable a recipe that is not approved."},
                status=status.HTTP_409_CONFLICT,
            )

        recipe.latest_revision.refresh_from_db()
        return Response(RecipeSerializer(recipe).data) 
Example #10
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_dry_run_process_conflict(self):
        """Tests error response when calling the Scan process view for a dry run Scan when already processed."""

        self.scan.job = job_utils.create_job()
        self.scan.save()

        url = '/%s/scans/%d/process/' % (self.api, self.scan.id)
        response = self.client.generic('POST', url, json.dumps({ 'ingest': False }), 'application/json')
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.content) 
Example #11
Source File: api_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_add_channel_channel_already_exists(mock_staff_client, patched_users_api):
    """Channel already exists with that channel name"""
    response_409 = Response()
    response_409.status_code = statuses.HTTP_409_CONFLICT
    mock_staff_client.channels.create.return_value = response_409

    title = "title"
    name = "name"
    description = "public description"
    channel_type = "private"
    input_search = Search.from_dict({"unmodified": "search"})
    role = RoleFactory.create()
    mod = UserFactory.create()

    with pytest.raises(ChannelAlreadyExistsException):
        api.add_channel(
            original_search=input_search,
            title=title,
            name=name,
            description=description,
            channel_type=channel_type,
            program_id=role.program.id,
            creator_id=mod.id,
        )

    mock_staff_client.channels.create.assert_called_once_with(
        title=title,
        name=name,
        description=description,
        channel_type=channel_type,
    ) 
Example #12
Source File: views.py    From drf-tus with MIT License 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        # Retrieve object
        upload = self.get_object()

        # When the upload is still saving, we're not able to destroy the entity
        if upload.state == states.SAVING:
            return Response(_('Unable to terminate upload while in state "{}".'.format(upload.state)),
                            status=status.HTTP_409_CONFLICT)

        # Destroy object
        self.perform_destroy(upload)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #13
Source File: collection_permission_assignment.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        object_permission = self.get_object()
        user = object_permission.user
        if user.pk == self.collection.owner_id:
            return Response({
                'detail': _("Owner's permissions cannot be deleted")
            }, status=status.HTTP_409_CONFLICT)

        codename = object_permission.permission.codename
        self.collection.remove_perm(user, codename)
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #14
Source File: asset_permission_assignment.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        object_permission = self.get_object()
        user = object_permission.user
        if user.pk == self.asset.owner_id:
            return Response({
                'detail': _("Owner's permissions cannot be deleted")
            }, status=status.HTTP_409_CONFLICT)

        codename = object_permission.permission.codename
        self.asset.remove_perm(user, codename)
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #15
Source File: test_api_hook.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_data_submission(self):
        # Create first hook
        first_hook = self._create_hook(name="dummy external service",
                                       endpoint="http://dummy.service.local/",
                                       settings={})
        responses.add(responses.POST, first_hook.endpoint,
                      status=status.HTTP_200_OK,
                      content_type="application/json")
        hook_signal_url = reverse("hook-signal-list", kwargs={"parent_lookup_asset": self.asset.uid})

        submissions = self.asset.deployment.get_submissions(self.asset.owner.id)
        data = {"instance_id": submissions[0].get(
            self.asset.deployment.INSTANCE_ID_FIELDNAME)}
        response = self.client.post(hook_signal_url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        # Create second hook
        second_hook = self._create_hook(name="other dummy external service",
                                        endpoint="http://otherdummy.service.local/",
                                        settings={})
        responses.add(responses.POST, second_hook.endpoint,
                      status=status.HTTP_200_OK,
                      content_type="application/json")

        response = self.client.post(hook_signal_url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

        response = self.client.post(hook_signal_url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)

        data = {'instance_id': 4}  # Instance doesn't belong to `self.asset`
        response = self.client.post(hook_signal_url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example #16
Source File: exceptions.py    From lego with MIT License 5 votes vote down vote up
def exception_handler(exc, context):
    """
    Return special responses on exceptions not supported by drf.
    """
    response = drf_exception_handler(exc, context)

    # Check for IntegrityError, use a custom status code for this.
    if not response and isinstance(exc, IntegrityError):
        set_rollback()
        response = Response(
            {"detail": "Some values are supposed to be unique but are not."},
            status=status.HTTP_409_CONFLICT,
        )

    if response:
        detail = None
        if isinstance(response.data, dict):
            detail = response.data.get("detail")

        log.warn(
            "request_error", status_code=response.status_code, detail=detail, exc=exc
        )
    else:
        log.error("unhandled_request_exception", exc=exc)

    return response 
Example #17
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_ingest_process_conflict(self):
        """Tests error response when calling the Scan process view for an ingest Scan when already processed."""

        self.scan.job = job_utils.create_job()
        self.scan.save()

        url = '/%s/scans/%d/process/' % (self.api, self.scan.id)
        response = self.client.generic('POST', url, json.dumps({ 'ingest': True }), 'application/json')
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.content) 
Example #18
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_edit_config_conflict(self):
        """Tests editing the configuration of a Scan process already launched"""

        json_data = {
            'configuration': {},
        }

        self.scan.job = job_utils.create_job()
        self.scan.save()
        url = '/%s/scans/%d/' % (self.api, self.scan.id)
        response = self.client.generic('PATCH', url, json.dumps(json_data), 'application/json')
        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT, response.content)

        result = json.loads(response.content)
        self.assertEqual(result['detail'], 'Ingest Scan already launched') 
Example #19
Source File: tests_query_objective.py    From substra-backend with Apache License 2.0 5 votes vote down vote up
def test_add_objective_conflict(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 = {'pkhash': pkhash}

            response = self.client.post(url, data, format='multipart', **extra)
            r = response.json()

            self.assertEqual(r['pkhash'], pkhash)
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

            # XXX reload data as the previous call to post change it
            _, data = self.get_default_objective_data()
            response = self.client.post(url, data, format='multipart', **extra)
            r = response.json()

            self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
            self.assertEqual(r['pkhash'], pkhash) 
Example #20
Source File: datasample.py    From substra-backend with Apache License 2.0 5 votes vote down vote up
def _create(self, request, data_manager_keys, test_only):

        # compute_data will uncompress data archives to paths which will be
        # hardlinked thanks to datasample pre_save signal.
        # In all other cases, we need to remove those references.

        if not data_manager_keys:
            raise Exception("missing or empty field 'data_manager_keys'")

        self.check_datamanagers(data_manager_keys)  # can raise

        paths_to_remove = []

        try:
            # will uncompress data archives to paths
            computed_data = self.compute_data(request, paths_to_remove)

            serializer = self.get_serializer(data=computed_data, many=True)

            try:
                serializer.is_valid(raise_exception=True)
            except Exception as e:
                pkhashes = [x['pkhash'] for x in computed_data]
                st = status.HTTP_400_BAD_REQUEST
                if find_primary_key_error(e):
                    st = status.HTTP_409_CONFLICT
                raise ValidationException(e.args, pkhashes, st)
            else:

                # create on ledger + db
                ledger_data = {'test_only': test_only,
                               'data_manager_keys': data_manager_keys}
                data, st = self.commit(serializer, ledger_data)  # pre_save signal executed
                return data, st
        finally:
            for gpath in paths_to_remove:
                shutil.rmtree(gpath, ignore_errors=True) 
Example #21
Source File: objective.py    From substra-backend with Apache License 2.0 5 votes vote down vote up
def _create(self, request):
        metrics = request.data.get('metrics')
        description = request.data.get('description')

        try:
            pkhash = get_hash(description)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            raise ValidationException(e.args, '(not computed)', st)

        serializer = self.get_serializer(data={
            'pkhash': pkhash,
            'metrics': metrics,
            'description': description,
        })

        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            st = status.HTTP_400_BAD_REQUEST
            if find_primary_key_error(e):
                st = status.HTTP_409_CONFLICT
            raise ValidationException(e.args, pkhash, st)
        else:
            # create on ledger + db
            return self.commit(serializer, request) 
Example #22
Source File: test_dyndns12update.py    From desec-stack with MIT License 5 votes vote down vote up
def test_identification_by_token(self):
        """
        Test if the conflict of having multiple domains, but not specifying which to update is correctly recognized.
        """
        self.client.set_credentials_basic_auth('', self.token.plain)
        response = self.client.get(self.reverse('v1:dyndns12update'), REMOTE_ADDR='10.5.5.7')
        self.assertStatus(response, status.HTTP_409_CONFLICT) 
Example #23
Source File: test_user_management.py    From desec-stack with MIT License 5 votes vote down vote up
def assertDeleteAccountFailureStillHasDomainsResponse(self, response):
        return self.assertContains(
            response=response,
            text="To delete your user account, first delete all of your domains.",
            status_code=status.HTTP_409_CONFLICT
        ) 
Example #24
Source File: mixins.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        """Create a resource."""
        self.define_contributor(request)

        try:
            return super().create(request, *args, **kwargs)

        except IntegrityError as ex:
            return Response({"error": str(ex)}, status=status.HTTP_409_CONFLICT) 
Example #25
Source File: views.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def disable(self, request, pk=None):
        recipe = self.get_object()

        try:
            recipe.approved_revision.disable(user=request.user)
        except EnabledState.NotActionable as e:
            return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT)

        recipe.latest_revision.refresh_from_db()
        return Response(RecipeSerializer(recipe).data) 
Example #26
Source File: hook_signal.py    From kpi with GNU Affero General Public License v3.0 4 votes vote down vote up
def create(self, request, *args, **kwargs):
        """
        It's only used to trigger hook services of the Asset (so far).

        :param request:
        :return:
        """
        try:
            instance_id = positive_int(
                request.data.get('instance_id'), strict=True)
        except ValueError:
            raise serializers.ValidationError(
                {'instance_id': _('A positive integer is required.')})

        # Check if instance really belongs to Asset.
        try:
            instance = self.asset.deployment.get_submission(instance_id,
                                                            request.user.id)
        except ValueError:
            raise Http404

        instance_id_fieldname = self.asset.deployment.INSTANCE_ID_FIELDNAME
        if not (instance and
                int(instance.get(instance_id_fieldname)) == instance_id):
            raise Http404

        if HookUtils.call_services(self.asset, instance_id):
            # Follow Open Rosa responses by default
            response_status_code = status.HTTP_202_ACCEPTED
            response = {
                "detail": _(
                    "We got and saved your data, but may not have "
                    "fully processed it. You should not try to resubmit.")
            }
        else:
            # call_services() refused to launch any task because this
            # instance already has a `HookLog`
            response_status_code = status.HTTP_409_CONFLICT
            response = {
                "detail": _(
                    "Your data for instance {} has been already "
                    "submitted.".format(instance_id))
            }

        return Response(response, status=response_status_code) 
Example #27
Source File: views.py    From cykel with MIT License 4 votes vote down vote up
def start_rent(request):
    bike_number = request.data.get("bike_number")
    # station = request.data.get("station")
    lat = request.data.get("lat")
    lng = request.data.get("lng")
    if not (bike_number):
        return Response({"error": "bike_number missing"}, status=400)
    # if (not lat or not lng) and (not station):
    #    return Response({"error": "lat and lng or station required"}, status=400)

    try:
        bike = Bike.objects.get(bike_number=bike_number)
    except Bike.DoesNotExist:
        return Response(
            {"error": "bike does not exist"}, status=status.HTTP_404_NOT_FOUND
        )

    # #TODO: message for bikes who are lost
    # if (bike.state == 'MI'):
    #     errortext = """We miss this bike.
    #       Please bring it to the bike tent at the Open Village"""
    #     if (bike.lock):
    #         if (bike.lock.lock_type == "CL" and bike.lock.unlock_key):
    #             errortext = """We miss this bike.
    #               Please bring it to the bike tent at the Open Village.
    #               Unlock key is """ + bike.lock.unlock_key
    #
    #     return Response({"error": errortext}, status=400)

    # check bike availability and set status to "in use"
    if bike.availability_status != "AV":
        return Response(
            {"error": "bike is not available"}, status=status.HTTP_409_CONFLICT
        )
    bike.availability_status = "IU"
    bike.save()

    rent = Rent.objects.create(rent_start=now(), user=request.user, bike=bike)
    if lat and lng:
        rent.start_position = Point(float(lng), float(lat), srid=4326)

        loc = Location.objects.create(bike=bike, source="US", reported_at=now())
        loc.geo = Point(float(lng), float(lat), srid=4326)
        loc.save()
    else:
        if bike.public_geolocation():
            rent.start_position = bike.public_geolocation().geo
        if bike.current_station:
            rent.start_station = bike.current_station
    rent.save()

    serializer = RentSerializer(rent)
    return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example #28
Source File: objective.py    From substra-backend with Apache License 2.0 4 votes vote down vote up
def commit(self, serializer, request):
        # create on local db
        try:
            instance = self.perform_create(serializer)
        except IntegrityError as e:
            try:
                pkhash = re.search(r'\(pkhash\)=\((\w+)\)', e.args[0]).group(1)
            except IndexError:
                pkhash = ''
            err_msg = 'A objective with this description file already exists.'
            return {'message': err_msg, 'pkhash': pkhash}, status.HTTP_409_CONFLICT
        except Exception as e:
            raise Exception(e.args)

        # init ledger serializer
        ledger_data = {
            'test_data_sample_keys': request.data.get('test_data_sample_keys') or [],
            'test_data_manager_key': request.data.get('test_data_manager_key', ''),
            'name': request.data.get('name'),
            'permissions': request.data.get('permissions'),
            'metrics_name': request.data.get('metrics_name'),
            'metadata': request.data.get('metadata')
        }
        ledger_data.update({'instance': instance})
        ledger_serializer = LedgerObjectiveSerializer(data=ledger_data,
                                                      context={'request': request})

        if not ledger_serializer.is_valid():
            # delete instance
            instance.delete()
            raise ValidationError(ledger_serializer.errors)

        # create on ledger
        try:
            data = ledger_serializer.create(ledger_serializer.validated_data)
        except LedgerTimeout as e:
            data = {'pkhash': [x['pkhash'] for x in serializer.data], 'validated': False}
            raise LedgerException(data, e.status)
        except LedgerConflict as e:
            raise ValidationException(e.msg, e.pkhash, e.status)
        except LedgerError as e:
            instance.delete()
            raise LedgerException(str(e.msg), e.status)
        except Exception:
            instance.delete()
            raise

        d = dict(serializer.data)
        d.update(data)

        return d 
Example #29
Source File: handlers.py    From product-definition-center with MIT License 4 votes vote down vote up
def exception_handler(exc, context):
    """
    This handler will overwrite rest framework default handler, additionally,
    it will process ValidationError (most of them were raised by
    django.db.models and django.forms), DB error (Refs PEP249).

    Show some details about the error, if it's safe. It could be more useful
    when the server does not work well in production env.

    Setting the `exception` attribute on the response is not necessary as it
    will be done by REST Framework.
    """
    response = views.exception_handler(exc, context)

    if response is None:
        if isinstance(exc, (exceptions.ValidationError, exceptions.FieldError)):
            # value is not correct or name is invalid.
            msg = exc.messages if hasattr(exc, 'messages') else str(exc)
            return Response({'detail': msg},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, exceptions.ObjectDoesNotExist):
            return Response({'detail': 'Not found:  %s' % str(exc)},
                            status=status.HTTP_404_NOT_FOUND)
        elif isinstance(exc, ProtectedError):
            return Response({"detail": "%s %s" % exc.args},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, ValueError):
            return Response({'detail': str(exc)},
                            status=status.HTTP_400_BAD_REQUEST)
        elif isinstance(exc, db.IntegrityError):
            # Refs PEP249
            # Maybe a duplicate PK, FK check fails, index conflict.
            return Response({'detail': str(exc)},
                            status=status.HTTP_409_CONFLICT)
        elif isinstance(exc, db.DatabaseError):
            # Refs PEP249
            # Other DB errors, such as incorrect grammar, transaction error etc.
            return Response({'detail': 'The database encountered an internal '
                                       'error or misconfiguration and was '
                                       'unable to complete your request.'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            logger = logging.getLogger(__name__)
            logger.error('Unhandled exception', exc_info=sys.exc_info())
            return Response(data=settings.INTERNAL_SERVER_ERROR_RESPONSE,
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)
    return response 
Example #30
Source File: views.py    From desec-stack with MIT License 4 votes vote down vote up
def _find_domain(self, request):
        def find_domain_name(r):
            # 1. hostname parameter
            if 'hostname' in r.query_params and r.query_params['hostname'] != 'YES':
                return r.query_params['hostname']

            # 2. host_id parameter
            if 'host_id' in r.query_params:
                return r.query_params['host_id']

            # 3. http basic auth username
            try:
                domain_name = base64.b64decode(
                    get_authorization_header(r).decode().split(' ')[1].encode()).decode().split(':')[0]
                if domain_name and '@' not in domain_name:
                    return domain_name
            except IndexError:
                pass
            except UnicodeDecodeError:
                pass
            except binascii.Error:
                pass

            # 4. username parameter
            if 'username' in r.query_params:
                return r.query_params['username']

            # 5. only domain associated with this user account
            if len(r.user.domains.all()) == 1:
                return r.user.domains.all()[0].name
            if len(r.user.domains.all()) > 1:
                ex = ValidationError(detail={
                    "detail": "Request does not specify domain unambiguously.",
                    "code": "domain-ambiguous"
                })
                ex.status_code = status.HTTP_409_CONFLICT
                raise ex

            return None

        name = find_domain_name(request).lower()

        try:
            return self.request.user.domains.get(name=name)
        except models.Domain.DoesNotExist:
            return None