Python rest_framework.exceptions.APIException() Examples

The following are 30 code examples of rest_framework.exceptions.APIException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.exceptions , or try the search function .
Example #1
Source File: models.py    From desec-stack with MIT License 6 votes vote down vote up
def update_delegation(self, child_domain: Domain):
        child_subname, child_domain_name = child_domain._partitioned_name
        if self.name != child_domain_name:
            raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
                             (child_domain.name, self.name))

        if child_domain.pk:
            # Domain real: set delegation
            child_keys = child_domain.keys
            if not child_keys:
                raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)

            RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
            RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
                                 contents=[ds for k in child_keys for ds in k['ds']])
            metrics.get('desecapi_autodelegation_created').inc()
        else:
            # Domain not real: remove delegation
            for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
                rrset.delete()
            metrics.get('desecapi_autodelegation_deleted').inc() 
Example #2
Source File: api.py    From code-review with Mozilla Public License 2.0 6 votes vote down vote up
def get_queryset(self):

        queryset = (
            Issue.objects.values(
                "analyzer", "check", "diff__revision__repository__slug"
            )
            .annotate(total=Count("id"))
            .annotate(
                publishable=Count("id", filter=Q(in_patch=True) | Q(level=LEVEL_ERROR))
            )
            .prefetch_related("diff", "diff_revision", "diff__revision__repository")
        )

        # Filter issues by date
        since = self.request.query_params.get("since")
        if since is not None:
            try:
                since = datetime.strptime(since, "%Y-%m-%d").date()
            except ValueError:
                raise APIException(detail="invalid since date - should be YYYY-MM-DD")
            queryset = queryset.filter(diff__created__gte=since)

        return queryset.order_by("-total") 
Example #3
Source File: request.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def _authenticate(self):
        """
        Attempt to authenticate the request using each authentication instance
        in turn.
        """
        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated() 
Example #4
Source File: update_views.py    From texta with GNU General Public License v3.0 6 votes vote down vote up
def elastic_update_request(item: dict) -> dict:
        try:
            elastic = elasticsearch.Elasticsearch(es_url)
            response = elastic.update(
                index=item["index"],
                doc_type=item["doc_type"] if "doc_type" in item else item["index"],
                id=item["id"],
                body={"doc": item["changes"]}
            )
            return response

        except elasticsearch.TransportError as e:
            # Will return the appropriate error message along with the status code.
            logging.getLogger(ERROR_LOGGER).exception(e)
            raise ElasticTransportError(e.error)

        except Exception as e:
            logging.getLogger(ERROR_LOGGER).exception(e)
            raise APIException("There has been an unidentified error in the backend, please contact the developers about this issue.") 
Example #5
Source File: exception.py    From ws-backend-community with GNU General Public License v3.0 6 votes vote down vote up
def web_sight_exception_handler(exc, context):
    """
    This is a custom Django exception handler that handles all exceptions thrown by the Web Sight REST
    API.
    :param exc: The exception that was thrown.
    :param context: The context in which the exception was thrown.
    :return: A response to return to the requesting user.
    """
    if isinstance(exc, IntegrityError):
        return handle_integrity_error(exc, context)
    elif isinstance(exc, ValidationError):
        return handle_validation_error(exc, context)
    elif isinstance(exc, WsRestNonFieldException):
        return handle_non_field_error(exc, context)
    elif isinstance(exc, APIException):
        return handle_api_exception(exc, context)
    else:
        return None 
Example #6
Source File: bindings.py    From channels-api with MIT License 6 votes vote down vote up
def run_action(self, action, pk, data):
        try:
            if not self.has_permission(self.user, action, pk):
                self.reply(action, errors=['Permission Denied'], status=401,
                           request_id=self.request_id)
            elif action not in self.available_actions:
                self.reply(action, errors=['Invalid Action'], status=400,
                           request_id=self.request_id)
            else:
                methodname = self.available_actions[action]
                method = getattr(self, methodname)
                detail = getattr(method, 'detail', True)
                if detail:
                    rv = method(pk, data=data)
                else:
                    rv = method(data=data)
                data, status = rv
                self.reply(action, data=data, status=status, request_id=self.request_id)
        except APIException as ex:
            self.reply(action, errors=self._format_errors(ex.detail), status=ex.status_code, request_id=self.request_id) 
Example #7
Source File: initialize.py    From cmdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
def add_viewset(table):
    data_index = table.name
    record_data_index = "{}.".format(table.name)
    deleted_data_index = "{}..".format(table.name)

    def list(self, request, *args, **kwargs):
        page = int(request.query_params.get("page", 1))
        page_size = int(request.query_params.get("page_size", 10))
        try:
            res = es.search(index=deleted_data_index, doc_type="deleted-data", size=page_size, from_=(page-1)*page_size)
        except Exception as exc:
            raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc)))
        return Response(res["hits"])

    def retrieve(self, request, *args, **kwargs):
        try:
            res = es.get(index=deleted_data_index, doc_type="data", id=kwargs["pk"])
        except NotFoundError as exc:
            raise exceptions.NotFound("Document {} was not found in Type {} of Index {}".format(kwargs["pk"], "data", table.name))
    viewset = type(table.name, (mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet),
                   dict(permission_classes=(c_permissions.TableLevelPermission, ), list=list, retrieve=retrieve))
    setattr(views, table.name, viewset)
    return viewset 
Example #8
Source File: views.py    From cmdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        try:
            res = es.get(index="test_12", doc_type="one", id=kwargs["pk"])
            data = res["_source"]
            data["S_delete_time"] = datetime.datetime.now().isoformat()
            data["S_delete_people"] = request.user.username
            res = es.create(index="test_32", doc_type="one", id=kwargs["pk"], body=data)
            es.delete(index="test_12", doc_type="one", id=kwargs["pk"])
            es.delete_by_query(index="test_22", doc_type="one", body={"query": {"match": {"S_data_id": kwargs["pk"]}}})
        except NotFoundError as exc:
            raise exceptions.ParseError("Document {} was not found in Type one of Index test_12".format(kwargs["pk"]))
        except Exception as exc:
            raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc)))
        return Response(res, status=status.HTTP_204_NO_CONTENT)

# t = TestViewset()
# t.paginate_queryset() 
Example #9
Source File: api.py    From ontask_b with MIT License 6 votes vote down vote up
def post(
        self,
        request: http.HttpRequest,
        wid: int,
        format=None,
        workflow: Optional[models.Workflow] = None,
    ) -> http.HttpResponse:
        """Create a new data frame."""
        if pandas.load_table(workflow.get_data_frame_table_name()) is not None:
            raise APIException(
                _('Post request requires workflow without a table'))
        return self.override(
            request,
            wid=wid,
            format=format,
            workflow=workflow) 
Example #10
Source File: serializers.py    From ontask_b with MIT License 6 votes vote down vote up
def extra_validation(self, validated_data):
        """Check that the token is present before execution."""
        super().extra_validation(validated_data)

        action = validated_data['action']
        if action.action_type != models.Action.PERSONALIZED_JSON:
            raise APIException(_('Incorrect type of action to schedule.'))

        payload = validated_data['payload']
        item_column_name = payload.get('item_column')
        if not item_column_name:
            raise APIException(
                _('Personalized text need a column name in payload '
                  'field item_column.'))

        item_column = action.workflow.columns.filter(
            name=item_column_name).first()
        if not item_column:
            raise APIException(
                _('Incorrect column name in field item_column.'))
        payload['item_column'] = item_column.id

        if not payload.get('token'):
            raise APIException(_(
                'Personalized JSON needs a token in payload.')) 
Example #11
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_fields(self):
        """
        Set field readonly if form field is disabled
        """
        serializer_fields = super().get_fields()
        try:
            model_form = self.model_form_class(instance=self.instance)
        except Exception as e:
            raise APIException(str(e))
        for field_name, form_field in model_form.fields.items():
            if field_name in serializer_fields:
                if form_field.disabled:
                    serializer_fields[field_name].read_only = True
                if form_field.required:
                    serializer_fields[field_name].required = True
                if form_field.help_text:
                    serializer_fields[field_name].help_text = form_field.help_text
        return serializer_fields 
Example #12
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """
        Delete specific App Variable by name
            Param:
                - name: str
        """
        var_name = request.data.get('name')

        if not var_name:
            raise APIException('Provide variable name to delete')

        AppVar.clear(var_name)
        return Response('OK')


# --------------------------------------------------------
# ReviewStatusGroup Views
# -------------------------------------------------------- 
Example #13
Source File: __init__.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def drf_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if not response and settings.CATCH_ALL_EXCEPTIONS:
        logging.exception(exc)
        exc = APIException(exc)
        response = exception_handler(exc, context)
    if response is not None:
        response.status_code = HTTP_200_OK
        if is_pretty(response):
            return response
        error_message = response.data.pop('detail', '')
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data['code'] = error_code
        response.data['message'] = error_message

    return response 
Example #14
Source File: views.py    From gro-api with GNU General Public License v2.0 6 votes vote down vote up
def state(self, request, pk=None):
        """
        Get the current state of the actuator
        ---
        serializer: gro_api.actuators.serializers.ActuatorStateSerializer
        """
        instance = self.get_object()
        try:
            queryset = ActuatorState.objects.filter(origin=instance).latest()
        except ObjectDoesNotExist:
            raise APIException(
                'No state has been recorded for this actuator yet'
            )
        serializer = ActuatorStateSerializer(
            queryset, context={'request': request}
        )
        return Response(serializer.data) 
Example #15
Source File: views.py    From gro-api with GNU General Public License v2.0 6 votes vote down vote up
def value(self, request, pk=None):
        """
        Get the current value of the sensing point
        ---
        serializer: gro_api.sensors.serializers.DataPointSerializer
        """
        instance = self.get_object()
        try:
            queryset = DataPoint.objects.filter(sensing_point=instance).latest()
        except ObjectDoesNotExist:
            raise APIException(
                'No data has been recorded for this sensor yet'
            )
        serializer = DataPointSerializer(
            queryset, context={'request': request}
        )
        return Response(serializer.data) 
Example #16
Source File: consumers.py    From djangochannelsrestframework with MIT License 6 votes vote down vote up
def handle_exception(self, exc: Exception, action: str, request_id):
        """
        Handle any exception that occurs, by sending an appropriate message
        """
        if isinstance(exc, APIException):
            await self.reply(
                action=action,
                errors=self._format_errors(exc.detail),
                status=exc.status_code,
                request_id=request_id,
            )
        elif exc == Http404 or isinstance(exc, Http404):
            await self.reply(
                action=action,
                errors=self._format_errors("Not found"),
                status=404,
                request_id=request_id,
            )
        else:
            raise exc 
Example #17
Source File: handlers.py    From drf-friendly-errors with MIT License 6 votes vote down vote up
def friendly_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if not response and settings.CATCH_ALL_EXCEPTIONS:
        exc = APIException(exc)
        response = exception_handler(exc, context)

    if response is not None:
        if is_pretty(response):
            return response
        error_message = response.data['detail']
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data.pop('detail', {})
        response.data['code'] = error_code
        response.data['message'] = error_message
        response.data['status_code'] = response.status_code
        # response.data['exception'] = exc.__class__.__name__

    return response 
Example #18
Source File: exceptions.py    From controller with MIT License 6 votes vote down vote up
def custom_exception_handler(exc, context):
    # give more context on the error since DRF masks it as Not Found
    if isinstance(exc, Http404):
        set_rollback()
        return Response(str(exc), status=status.HTTP_404_NOT_FOUND)

    # Call REST framework's default exception handler after specific 404 handling,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # No response means DRF couldn't handle it
    # Output a generic 500 in a JSON format
    if response is None:
        logging.exception('Uncaught Exception', exc_info=exc)
        set_rollback()
        return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # log a few different types of exception instead of using APIException
    if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
        logging.exception(exc.__cause__, exc_info=exc)

    return response 
Example #19
Source File: __init__.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def drf_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if not response and settings.CATCH_ALL_EXCEPTIONS:
        logging.exception(exc)
        exc = APIException(exc)
        response = exception_handler(exc, context)
    if response is not None:
        response.status_code = HTTP_200_OK
        if is_pretty(response):
            return response
        error_message = response.data.pop('detail', '')
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data['code'] = error_code
        response.data['message'] = error_message

    return response 
Example #20
Source File: exceptions.py    From controller with MIT License 6 votes vote down vote up
def custom_exception_handler(exc, context):
    # give more context on the error since DRF masks it as Not Found
    if isinstance(exc, Http404):
        set_rollback()
        return Response(str(exc), status=status.HTTP_404_NOT_FOUND)

    # Call REST framework's default exception handler after specific 404 handling,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # No response means DRF couldn't handle it
    # Output a generic 500 in a JSON format
    if response is None:
        logging.exception('Uncaught Exception', exc_info=exc)
        set_rollback()
        return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # log a few different types of exception instead of using APIException
    if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
        logging.exception(exc.__cause__, exc_info=exc)

    return response 
Example #21
Source File: views.py    From drf-tracking with ISC License 5 votes vote down vote up
def get(self, request):
        raise APIException('with logging') 
Example #22
Source File: serializers.py    From openwisp-radius with GNU General Public License v3.0 5 votes vote down vote up
def is_sms_verification_enabled(self):
        org = self.context['view'].organization
        try:
            return org.radius_settings.sms_verification
        except ObjectDoesNotExist:
            raise APIException(
                'Could not complete operation '
                'because of an internal misconfiguration'
            ) 
Example #23
Source File: exceptions.py    From oldp with MIT License 5 votes vote down vote up
def full_details_exception_handler(exc, context):
    """
    This overrides the default exception handler to
    include the human-readable message AND the error code
    so that clients can respond programmatically.
    """
    if isinstance(exc, APIException):
        exc.detail = exc.get_full_details()

    return exception_handler(exc, context) 
Example #24
Source File: bindings.py    From channels-api with MIT License 5 votes vote down vote up
def get_object_or_404(self, pk):
        queryset = self.filter_queryset(self.get_queryset())
        filter_kwargs = {self.lookup_field: pk}
        try:
            return get_object_or_404(queryset, **filter_kwargs)
        except Http404:
            # transform Http404 into an APIException
            raise NotFound 
Example #25
Source File: api.py    From code-review with Mozilla Public License 2.0 5 votes vote down vote up
def get_queryset(self):

        # Count all the issues per day
        queryset = (
            Issue.objects.annotate(date=TruncDate("created"))
            .values("date")
            .annotate(total=Count("id"))
        )

        # Filter by repository
        repository = self.request.query_params.get("repository")
        if repository:
            queryset = queryset.filter(diff__revision__repository__slug=repository)

        # Filter by analyzer
        analyzer = self.request.query_params.get("analyzer")
        if analyzer:
            queryset = queryset.filter(analyzer=analyzer)

        # Filter by check
        check = self.request.query_params.get("check")
        if check:
            queryset = queryset.filter(check=check)

        # Filter by date
        since = self.request.query_params.get("since")
        if since is not None:
            try:
                since = datetime.strptime(since, "%Y-%m-%d").date()
            except ValueError:
                raise APIException(detail="invalid since date - should be YYYY-MM-DD")
            queryset = queryset.filter(date__gte=since)

        return queryset.order_by("date")


# Build exposed urls for the API 
Example #26
Source File: views.py    From drf-tracking with ISC License 5 votes vote down vote up
def get(self, request):
        raise APIException('response') 
Example #27
Source File: exception.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def handle_api_exception(exc, context):
    """
    Handle the given APIException.
    :param exc: The exception that was thrown.
    :param context: The context in which the exception was thrown.
    :return: A Django Response object.
    """
    response = exception_handler(exc, context)
    response.data = {
        "status_code": response.status_code,
        "message": "Exception thrown",
        "detail": exc.detail,
        "error_fields": [],
    }
    return response 
Example #28
Source File: metadata.py    From product-definition-center with MIT License 5 votes vote down vote up
def determine_actions(self, request, view):
        """
        For generic class based views we return information about the fields
        that are accepted for 'PUT' and 'POST' methods.

        This method expects that `get_object` may actually fail and gracefully
        handles it.

        Most of the code in this method is copied from the parent class.
        """
        actions = {}
        for method in set(['PUT', 'POST']) & set(view.allowed_methods):
            view.request = clone_request(request, method)
            try:
                # Test global permissions
                if hasattr(view, 'check_permissions'):
                    view.check_permissions(view.request)
                # Test object permissions. This will fail on list url for
                # resources supporting bulk operations. In such case
                # permissions are not checked.
                if method == 'PUT' and hasattr(view, 'get_object'):
                    try:
                        view.get_object()
                    except (AssertionError, KeyError):
                        pass
            except (exceptions.APIException, PermissionDenied, Http404):
                pass
            else:
                # If user has appropriate permissions for the view, include
                # appropriate metadata about the fields that should be supplied.
                serializer = view.get_serializer()
                actions[method] = self.get_serializer_info(serializer)
            finally:
                view.request = request

        return actions 
Example #29
Source File: views.py    From indrz with GNU General Public License v3.0 5 votes vote down vote up
def poi_list(request, campus_id, format=None):
    try:
        poi_qs = Poi.objects.filter(enabled=True)
        serializer = PoiSerializer(poi_qs, many=True)
        return Response(serializer.data)

    except Exception as e:
        raise APIException(detail=e) 
Example #30
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.
    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.
    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None