如何在Django REST Framework中找不到资源时如何返回404

时间:2017-02-03 20:39:28

标签: django django-rest-framework http-status-code-404

当用户输入错误的网址时,我的Django应用会返回HTML错误。如何让DRF返回json格式的错误?

目前我的网址是

df <- data.frame(startBin = c(1,1,1,1), endBin = c(26,26,26,26), exprTemp=c("One","Two","Three","Four")) 

condition= c("startBin>7 & startBin<=12 & endBin>25 & endBin<=30","(startBin<=7 | startBin>12) & (endBin<=25 | endBin>30)","(startBin>7 & startBin<=12) & (endBin<=25 | endBin>30)","(startBin<=7 | startBin>12) & endBin>25 & endBin<=30")
parsedcond=(parse(text = condition))

newcol=logical(nrow(df))
for(i in 1:nrow(df))
 newcol[i] <- with(df, eval(parsedcond[i]))[i]

    df <- data.frame(df, newcol)
> df
  startBin endBin exprTemp newcol
1        1     26      One  FALSE
2        1     26      Two  FALSE
3        1     26    Three  FALSE
4        1     26     Four   TRUE

但是如果用户转到127.0.0.1:8000/snip他们会得到html格式的错误而不是json格式的错误。

3 个答案:

答案 0 :(得分:17)

只需这样做,就可以使用raise Http404,这是您的views.py

from django.http import Http404

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from yourapp.models import Snippet
from yourapp.serializer import SnippetSerializer


class SnippetDetailView(APIView):

    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data, status=status.HTTP_200_OK)

你也可以使用Response(status=status.HTTP_404_NOT_FOUND)处理它,这个答案是如何处理的:https://stackoverflow.com/a/24420524/6396981

但之前,在serializer.py

from rest_framework import serializers

from yourapp.models import Snippet


class SnippetSerializer(serializers.ModelSerializer):
    user = serializers.CharField(
        source='user.pk',
        read_only=True
    )
    photo = serializers.ImageField(
        max_length=None,
        use_url=True
    )
    ....

    class Meta:
        model = Snippet
        fields = ('user', 'title', 'photo', 'description')

    def create(self, validated_data):
        return Snippet.objects.create(**validated_data)

要测试它,使用curl命令的示例;

$ curl -X GET http://localhost:8000/snippets/<pk>/

# example;

$ curl -X GET http://localhost:8000/snippets/99999/

希望它可以帮助..

更新

如果您想处理所有带有DRF的错误404网址,DRF也会提供APIException,这个答案可能对您有所帮助; https://stackoverflow.com/a/30628065/6396981

我将举例说明如何使用它;

<强> 1。 views.py

from rest_framework.exceptions import NotFound

def error404(request):
    raise NotFound(detail="Error 404, page not found", code=404)

<强> 2。 urls.py

from django.conf.urls import (
  handler400, handler403, handler404, handler500)

from yourapp.views import error404

handler404 = error404
  

确认您的DEBUG = False

答案 1 :(得分:4)

from rest_framework import status    
from rest_framework.response import Response

# return 404 status code    
return Response({'status': 'details'}, status=status.HTTP_404_NOT_FOUND)

答案 2 :(得分:0)

或者简单地说,您可以使用相同的DRF结构,而不会丢失I18N并保留相同的DRF错误消息:

from rest_framework import viewsets, status, exceptions
from rest_framework.decorators import action
from rest_framework.response import Response

        try:

            codename = get_or_bad_request(self.request.query_params, 'myparam')
            return Response(self.get_serializer(MyModel.objects.get(myparam=codename), many=False).data)
        except MyModel.DoesNotExist as ex:
            exc = exceptions.NotFound()
            data = {'detail': exc.detail}
            return Response(data, exc.status_code)