Ejemplo n.º 1
0
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
 def test_static_renderer_with_exception(self):
     context = {
         'response': Response(status=500, exception=True),
         'request': Request(HttpRequest())
     }
     result = self.renderer.render({}, renderer_context=context)
     assert result == '500 Internal Server Error'
Ejemplo n.º 3
0
 def post(self, request, *args, **kwargs):
     serializer = self.serializer_class(data=request.data,
                                        context={'request': request})
     serializer.is_valid(raise_exception=True)
     user = serializer.validated_data['user']
     token, created = Token.objects.get_or_create(user=user)
     return Response({'token': token.key})
Ejemplo n.º 4
0
 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     self.kwargs['key'] = serializer.validated_data['key']
     confirmation = self.get_object()
     confirmation.confirm(self.request)
     return Response({'detail': _('ok')}, status=status.HTTP_200_OK)
 def post(self, request):
     username = request.data['username']
     password = request.data['password']
     user = authenticate(username=username, password=password)
     if user is None:
         return Response({'error': 'incorrect credentials'})
     login(request, user)
     return redirect('/auth/')
Ejemplo n.º 6
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     return Response(serializer.data,
                     status=status.HTTP_201_CREATED,
                     headers=headers)
Ejemplo n.º 7
0
 def options(self, request, *args, **kwargs):
     """
     Handler method for HTTP 'OPTIONS' request.
     """
     if self.metadata_class is None:
         return self.http_method_not_allowed(request, *args, **kwargs)
     data = self.metadata_class().determine_metadata(request, self)
     return Response(data, status=status.HTTP_200_OK)
    def post(self, request):
        filenames = [
            file.temporary_file_path() for file in request.FILES.values()
        ]

        for filename in filenames:
            assert os.path.exists(filename)

        return Response(status=status.HTTP_200_OK, data=filenames)
Ejemplo n.º 9
0
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 10
0
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
 def get(self, request):
     headers = {
         key[5:].replace('_', '-'): value
         for key, value in request.META.items()
         if key.startswith('HTTP_')
     }
     return Response({
         'method': request.method,
         'headers': headers
     })
    def post(self, request):
        if request.content_type:
            content_type = request.content_type.split(';')[0]
        else:
            content_type = None

        return Response({
            'method': request.method,
            'query_params': _get_query_params(request),
            'data': _get_data(request),
            'files': _get_files(request),
            'content_type': content_type
        })
Ejemplo n.º 13
0
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)
Ejemplo n.º 14
0
    def post(self, request, *args, **kwargs):
        accounts = self.get_queryset()
        account = accounts.filter(pk=kwargs['pk']).first()
        if not account:
            raise NotFound

        get_social_adapter(self.request).validate_disconnect(account, accounts)

        account.delete()
        signals.social_account_removed.send(
            sender=SocialAccount,
            request=self.request,
            socialaccount=account
        )

        return Response(self.get_serializer(account).data)
    def post(self, request):
        files = {
            key: (value.name, value.read())
            for key, value in request.FILES.items()
        }
        post = request.POST
        json = None
        if request.META.get('CONTENT_TYPE') == 'application/json':
            json = request.data

        return Response({
            'method': request.method,
            'query_params': request.query_params,
            'POST': post,
            'FILES': files,
            'JSON': json
        })
    def test_render_when_resource_created(self):
        class DummyView(APIView):
            renderer_classes = (AdminRenderer, )

        request = Request(HttpRequest())
        request.build_absolute_uri = lambda: 'http://example.com'
        response = Response(status=201, headers={'Location': '/test'})
        context = {
            'view': DummyView(),
            'request': request,
            'response': response
        }

        result = self.renderer.render(data={'test': 'test'},
                                      renderer_context=context)
        assert result == ''
        assert response.status_code == status.HTTP_303_SEE_OTHER
        assert response['Location'] == 'http://example.com'
Ejemplo n.º 17
0
    def get(self, request, *args, **kwargs):
        # Return a plain {"name": "hyperlink"} response.
        ret = OrderedDict()
        namespace = request.resolver_match.namespace
        for key, url_name in self.api_root_dict.items():
            if namespace:
                url_name = namespace + ':' + url_name
            try:
                ret[key] = reverse(url_name,
                                   args=args,
                                   kwargs=kwargs,
                                   request=request,
                                   format=kwargs.get('format', None))
            except NoReverseMatch:
                # Don't bail out if eg. no list routes exist, only detail routes.
                continue

        return Response(ret)
 def get(self, request, *args, **kwargs):
     return Response({'version': request.version})
 def regex_url_path_detail(self, request, *args, **kwargs):
     pk = self.kwargs.get('pk', '')
     kwarg = self.kwargs.get('kwarg', '')
     return Response({'pk': pk, 'kwarg': kwarg})
 def regex_url_path_list(self, request, *args, **kwargs):
     kwarg = self.kwargs.get('kwarg', '')
     return Response({'kwarg': kwarg})
 def detail_custom_route_get(self, request, *args, **kwargs):
     return Response({'method': 'link2'})
 def list_custom_route_get(self, request, *args, **kwargs):
     return Response({'method': 'link1'})
 def list(self, request, *args, **kwargs):
     return Response({'method': 'list'})
 def retrieve(self, request, *args, **kwargs):
     return Response({'hello': 'world'})
 def custom(self, request, *args, **kwargs):
     return Response(
         {'permission_classes': self.permission_classes})
 def get(self, request, *args, **kwargs):
     return Response({'url': reverse('another', request=request)})
 def exception_handler(exc, request):
     data = exc.get_codes()
     return Response(data, status=status.HTTP_400_BAD_REQUEST)
 def list_route_post(self, request, *args, **kwargs):
     return Response({'method': 'action1'})
Ejemplo n.º 29
0
 def get(self, request, *args, **kwargs):
     return Response(data={"ok": "test view"})
 def detail_route_post(self, request, *args, **kwargs):
     return Response({'method': 'action2'})