Пример #1
0
def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception

    Must be set in settings:

    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
    ...     # ...
    ... }

    For the parameters, see ``exception_handler``

    """

    if isinstance(exc, DjangoValidationError):
        try:
            exc = DRFValidationError(detail=exc.message_dict)
        except AttributeError:
            exc = DRFValidationError(detail={"validation_error": exc.message})

    if isinstance(exc, ProtectedError):
        exc = DRFValidationError(detail={"protection_error": exc.args[0]})

    return drf_exception_handler(exc, context)
Пример #2
0
def custom_exception_handler(exc, context):
    if isinstance(exc, PermissionDenied):
        exc = PermissionDenied(
            detail={'message': 'Ошибка доступа. У вас нет прав.'})

    if isinstance(exc, NotAuthenticated):
        exc = NotAuthenticated(
            detail={'message': 'Ошибка доступа. Вы не авторизованы'})

    if isinstance(exc, CustomValidation):
        field = list(exc.detail.keys())[0]
        exc = DRFValidationError(
            detail={'message': field + ' ' + exc.detail[field]})

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            # TODO: handle many fields
            field = list(exc.detail.keys())[0]

            exc = DRFValidationError(
                detail={'message': field + ' ' + exc.detail[field]})
        else:
            exc = DRFValidationError(detail={'message': exc.message})

    if isinstance(exc, DjangoIntegrityError):
        exc = DRFValidationError(detail={'message': str(exc)})

    return drf_exception_handler(exc, context)
    def create(self, request, *args, **kwargs):
        lti_session = getattr(self.request, 'LTI', {})
        audit_user_id = lti_session.get('custom_canvas_user_login_id')
        account_sis_id = lti_session.get('custom_canvas_account_sis_id')
        if not all((audit_user_id, account_sis_id)):
            raise DRFValidationError(
                'Invalid LTI session: custom_canvas_user_login_id and '
                'custom_canvas_account_sis_id required')

        account = self.request.data.get('account')
        term = self.request.data.get('term')
        if not all((account, term)):
            raise DRFValidationError('Both account and term are required')

        # for the moment, only the current school account can be operated on
        if not account_sis_id[len('school:'):] == account:
            raise PermissionDenied

        selected_courses = self.request.data.get('course_list')

        process = Process.enqueue(
            bulk_publish_canvas_sites,
            settings.RQWORKER_QUEUE_NAME,
            account='sis_account_id:school:{}'.format(account),
            term='sis_term_id:{}'.format(term),
            audit_user=audit_user_id,
            course_list=selected_courses)

        logger.debug('Enqueued Process job for bulk_publish_canvas_sites: '
                     '{}'.format(process))

        return Response(self.serializer_class(process).data,
                        status=status.HTTP_201_CREATED)
Пример #4
0
def exception_handler(exc, context):
    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail=exc.message_dict)
        else:
            exc = DRFValidationError(detail=exc.message)

    return drf_exception_handler(exc, context)
Пример #5
0
def convert_validation_error(error):
    """
    Convert a Django ValidationError to a DRF ValidationError.
    """
    # TODO: handle Django ValidationError properties other than message
    if hasattr(error, 'message'):
        return DRFValidationError(error.message)
    else:
        return DRFValidationError('Validation error on underlying data.')
Пример #6
0
def exception_handler(exc, context):

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})

    return drf_exception_handler(exc, context)
Пример #7
0
    def retrieve(self, request, pk=None):
        # Método para ver os detalhes de um usuário.
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            raise DRFValidationError('Usuário não encontrado.')

        if request.user and request.user.is_authenticated:
            serializer = UserSerializer(user)
        else:
            raise DRFValidationError('Você não tem acesso a este usuário.')
        return Response(serializer.data)
Пример #8
0
    def filter_queryset(self, request, queryset, view):
        if not 'order_by_distance_to' in request.query_params:
            return queryset

        try:
            coordinates = json.loads(request.query_params['order_by_distance_to'])
        except JSONDecodeError:
            raise DRFValidationError(detail=self.error_message)

        if not check_coordinates(coordinates):
            raise DRFValidationError(detail=self.error_message)

        return queryset.annotate(distance=DistanceFunction('coordinates', Point(coordinates, srid=4326))).order_by('distance')
def exception_handler(exc, context):
    """Custom exception handler for DRF (specified in ``settings.py``).
    Main use:
        > handling of django.core.ValidationError for better json returns of API
    """
    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, "message_dict"):
            exc = DRFValidationError(detail={"error": exc.message_dict})
        elif hasattr(exc, "message"):
            exc = DRFValidationError(detail={"error": exc.message})
        elif hasattr(exc, "messages"):
            exc = DRFValidationError(detail={"error": exc.messages})

    return drf_exception_handler(exc, context)
Пример #10
0
def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception
    For the parameters, see ``exception_handler``
    """

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})

    return drf_exception_handler(exc, context)
Пример #11
0
def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception."""

    if isinstance(exc, DjangoValidationError):
        exc = DRFValidationError(detail=exc.messages)

    return drf_exception_handler(exc, context)
Пример #12
0
 def post(self, request, *args, **kwargs):
     """ Create a new job from submitted params """
     if logger.isEnabledFor(logging.DEBUG):
         for key, param in request.data.items():
             logger.debug('param key ' + key + ' param:' + str(param))
     service_submission = self.get_object()
     passed_data = request.data.copy()
     ass_email = passed_data.pop('email', None)
     try:
         passed_data.pop('api_key', None)
         from ..serializers.jobs import JobCreateSerializer
         from django.db.models import Q
         job = Job.objects.create_from_submission(
             submission=service_submission,
             email_to=ass_email,
             submitted_inputs=passed_data,
             user=request.user)
         # Now job is created (or raise an exception),
         serializer = JobSerializer(job,
                                    many=False,
                                    context={'request': request},
                                    fields=(
                                        'slug',
                                        'url',
                                        'created',
                                        'status',
                                    ))
         return Response(serializer.data, status=201)
     except ValidationError as e:
         raise DRFValidationError(e.message_dict)
     except JobException as e:
         logger.fatal("Create Error %s", e.message)
         return Response({'error': e.message},
                         status=status.HTTP_400_BAD_REQUEST)
Пример #13
0
def exception_handler(exception, context):
    # Transform model validation errors into an equivalent DRF ValidationError.
    if isinstance(exception, DjangoValidationError):
        exception = DRFValidationError(detail=get_error_detail(exception))

    # Call REST Framework's default exception handler with the transformed exception.
    return drf_exception_handler(exception, context)
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    if isinstance(exc, DjangoValidationError):
        exc = DRFValidationError(detail=exc.message_dict)

    return drf_exception_handler(exc, context)
Пример #15
0
def exception_handler(exception, context):
    """Handle Django ValidationError as an accepted exception
    Must be set in settings:
    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'Authentication.exception_handler.exception_handler',
    ...     # ...
    ... }
    For the parameters, see ``exception_handler``
    """

    if isinstance(exception, DjangoValidationError):
        if isinstance(exception, DjangoValidationError):
            if hasattr(exception, 'message_dict'):
                detail = exception.message_dict
            elif hasattr(exception, 'message'):
                detail = exception.message
            elif hasattr(exception, 'messages'):
                detail = exception.messages
            else:
                logging.error("BAD VALIDATION MESSAGE: %s" % exception)

            exception = DRFValidationError(detail={"detail": detail})

    return drf_exception_handler(exception, context)
Пример #16
0
    def validate_username(self, username):

        user_with_username = User.objects.filter(username=username)

        if user_with_username.exists():
            raise DRFValidationError("Unable to create user.")
        return username
Пример #17
0
    def save(self):
        request = self.context['request']

        request_user = None
        if request.user and request.user.is_authenticated:
            request_user = request.user

        # Build application class and save record to DB to record the attempt
        Application = self.Meta.model
        app = Application(**self.validated_data)

        # Store the ip address of user sending the request
        app.ip_address, _ = get_client_ip(request)

        app.user = request_user
        app.submitting_user = request_user
        app.save()

        # Submit application to to Wells
        try:
            result = actions.submit_credit_application(
                app, current_user=request_user)
        except core_exceptions.CreditApplicationPending as e:
            pending = api_exceptions.CreditApplicationPending()
            pending.inquiry = e.inquiry
            raise pending
        except core_exceptions.CreditApplicationDenied:
            raise api_exceptions.CreditApplicationDenied()
        except DjangoValidationError as e:
            raise DRFValidationError({'non_field_errors': [e.message]})
        return result
Пример #18
0
def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception
    Must be set in settings:
    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
    ...     # ...
    ... }
    For the parameters, see ``exception_handler``
    """

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, "message_dict"):
            new_dict = {}
            for key, value in exc.message_dict.items():
                if type(value) in (list, tuple, set,
                                   frozenset) and len(value) == 1:
                    new_dict[key] = value[0]
                else:
                    new_dict[key] = value
            detail = new_dict
        elif hasattr(exc, "message"):
            detail = {'detail': exc.message}
        elif hasattr(exc, "messages"):
            detail = exc.messages
        else:
            return drf_exception_handler(exc, context)

        exc = DRFValidationError(detail=detail)

    return drf_exception_handler(exc, context)
Пример #19
0
    def list(self, request, *args, **kwargs):
        data = TransmissionForm(request.query_params)
        if not data.is_valid():
            raise DRFValidationError(data.errors)
        requested_timezone = data.cleaned_data.get('timezone')

        after = data.cleaned_data['after']
        before = data.cleaned_data['before']

        tz = requested_timezone or pytz.utc
        after_date = tz.localize(
            datetime.datetime.combine(after, datetime.time()))
        before_date = tz.localize(
            datetime.datetime.combine(before, datetime.time(23, 59, 59)))

        # Apply filters to the queryset
        schedules = self.filter_queryset(self.get_queryset())
        # Filter by active calendar if that filter was not provided
        if not data.cleaned_data.get('calendar'):
            schedules = schedules.filter(calendar__is_active=True)

        transmissions = Transmission.between(after_date,
                                             before_date,
                                             schedules=schedules)
        serializer = self.get_serializer(transmissions, many=True)
        with override(timezone=tz):
            return Response(serializer.data)
def extra_exception_handler(exc, context):
    # from https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f
    # Convert django ValidationError to DRF exceptions. This way, instead of
    # returning a 500 error it will return a 400
    if isinstance(exc, DjangoValidationError):
        errors = getattr(exc, "error_list", None) or getattr(
            exc, "error_dict", None)
        exc = DRFValidationError(detail=errors)

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

    # If response is None, add more cases to the exception handler.
    if response is None:
        if isinstance(exc, IntegrityError):
            data = {api_settings.NON_FIELD_ERRORS_KEY: str(exc)}
            return Response(data, status=status.HTTP_400_BAD_REQUEST)
        elif (isinstance(exc, APIException)
              and exc.status_code == status.HTTP_400_BAD_REQUEST):
            data = {
                api_settings.NON_FIELD_ERRORS_KEY:
                exc.get_full_details()["message"],
                "code":
                exc.get_codes(),
            }
            return Response(data, status=status.HTTP_400_BAD_REQUEST)

    # If the response has APIException inject the exception code in the response
    elif response and isinstance(exc, APIException) and exc.get_codes():
        response.data["code"] = exc.get_codes()

    return response
Пример #21
0
 def clean(self):
     self.tags = list(set(t.lower() for t in self.tags))
     if len(self.tags) > settings.CHANNEL_MAX_TAGS:
         raise DRFValidationError({
             'tags':
             ['Specify a maximum of '
              f'{settings.CHANNEL_MAX_TAGS} Tags.']
         })
Пример #22
0
 def __call__(self, value):
     try:
         validate(instance=value, schema=self.schema)
     except JSONSchemaValidationError:
         # Transform jsonschema ValidationError to DRF ValidationError
         raise DRFValidationError()
     else:
         return value
Пример #23
0
def rest_exception_handler(exc, context):
    if isinstance(exc, DjangoValidationError):
        if not settings.DEBUG:
            raise exc
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail={'error': exc.message_dict})
        elif hasattr(exc, 'message'):
            exc = DRFValidationError(detail={'error': exc.message})
        elif hasattr(exc, 'messages'):
            exc = DRFValidationError(detail={'error': exc.messages})

    response = exception_handler(exc, context)

    if response:
        response.data['status'] = response.status_code
        response.data['code'] = getattr(exc, 'code', getattr(exc, 'default_code', None)) or response.data['detail'].code
    return response
Пример #24
0
 def validate_query_params(self):
     if 'only_last_version' in self.query_params:
         if len([n for n in self.query_params if 'history_date' in n]) != 2:
             raise DRFValidationError(self.ONLY_LAST_VERSION_ERROR_MSG)
         self._validate_history_date()
     if 'cursor' in self.query_params:
         self._validate_cursor()
     return self.query_params
Пример #25
0
    def validiate_user_to_follow(self, user_to_follow):
        try:
            User.objects.get(pk=user_to_follow)
        except User.DoesNotExist:
            raise DRFValidationError(
                "User you are trying to follow does not exist.")

        return user_to_follow
Пример #26
0
    def validate_geometrie(self, value):
        fail_msg = 'Location coordinates not anywhere near Amsterdam. (in WGS84)'

        lat_not_in_adam_area = not 50 < value.coords[1] < 55
        lon_not_in_adam_area = not 1 < value.coords[0] < 7

        if lon_not_in_adam_area or lat_not_in_adam_area:
            raise DRFValidationError(fail_msg)
        return value
Пример #27
0
def exception_handler(exc, context):
    """Handle Django ValidationError as an accepted exception
    Must be set in settings:
    >>> REST_FRAMEWORK = {
    ...     # ...
    ...     'EXCEPTION_HANDLER': 'mtp.apps.common.drf.exception_handler',
    ...     # ...
    ... }
    For the parameters, see ``exception_handler``
    """

    if isinstance(exc, DjangoValidationError):
        if hasattr(exc, 'message_dict'):
            exc = DRFValidationError(detail=exc.message_dict)
        else:
            exc = DRFValidationError(detail=exc.message)

    return drf_exception_handler(exc, context)
Пример #28
0
 def _validate_assignments_data(self, assignments):
     """
     Raise ValidationError with specified message if `assignments` is not a list of dicts.
     """
     if not all(isinstance(item, dict) for item in assignments):
         raise DRFValidationError({
             'non_field_errors':
             ['Expected a list of items but got type "dict".']
         })
Пример #29
0
def exception_handler(exc, context):
    """
    https://gist.github.com/twidi/9d55486c36b6a51bdcb05ce3a763e79f
    This handler is used to change model validation error to serializer's validation error.
    """
    if isinstance(exc, DjangoValidationError):
        exc = DRFValidationError(detail=exc.message_dict)

    return drf_exception_handler(exc, context)
Пример #30
0
    def validate_geometrie(self, value):
        fail_msg = 'The location coordinates (WS84) are not inside the bounding box we are accepting signals for.'

        lat_not_in_bounding_box = not settings.BOUNDING_BOX[1] <= value.coords[1] <= settings.BOUNDING_BOX[3]
        lon_not_in_bounding_box = not settings.BOUNDING_BOX[0] <= value.coords[0] <= settings.BOUNDING_BOX[2]

        if lat_not_in_bounding_box or lon_not_in_bounding_box:
            raise DRFValidationError(fail_msg)

        return value