如果找不到 Django REST Framework 的详细信息

我试图实现这个答案Response来为我的所有类创建一个自定义基ModelViewSet类。我的问题在于retrieve功能。如果Id我正在寻找的实例没有找到,我似乎无法Response用我修改的response_format. 它仍然给出默认响应。我应该把我的if病情改成什么?

views.py:


class ResponseInfo(object):

    def __init__(self, **args):

        self.response = {

            "message": args.get('message', 'success'),

            "error": args.get('error', ),

            "data": args.get('data', []),

        }



class LanguageView(viewsets.ModelViewSet):

    def __init__(self, **kwargs):

        self.response_format = ResponseInfo().response

        super(LanguageView, self).__init__(**kwargs)


    permission_classes = [permissions.DjangoModelPermissions]

    queryset = Language.objects.all()

    serializer_class = LanguageSerializer


    def list(self, request, *args, **kwargs):

        # call the original 'list' to get the original response.

        response_data = super(LanguageView, self).list(request, *args, **kwargs)

        # customize the response data.

        self.response_format['data'] = response_data.data

        if not response_data.data:

            self.response_format['message'] = 'List is empty.'

            self.response_format['error'] = response_data.status_code

        return Response(self.response_format)


    def retrieve(self, request, *args, **kwargs):

        response_data = super(LanguageView, self).retrieve(request, *args, **kwargs)

        self.response_format['data'] = response_data.data

        if not response_data.data:

            self.response_format['message'] = 'Instance not found.'

            self.response_format['error'] = response_data.status_code

        return Response(self.response_format)

找到实例时的 JSON 响应。例如http://127.0.0.1:8000/languages/1/:


{

    "message": "success",

    "error": null,

    "data": {

        "id": 1,

        "name": "English",

        "icon": "http://127.0.0.1:8000/media/language_icons/English.png",

        "xml": "http://127.0.0.1:8000/media/-",

        "abbreviation": "En"

    }

}


"error"没有错误时是否可以不显示变量?对于这种情况,当列表不为空并且找到搜索的实例时。


慕妹3242003
浏览 76回答 1
1回答

莫回无

您可以实现自定义异常处理程序:from rest_framework.views import exception_handlerdef custom_exception_handler(exc, context):    # Call REST framework's default exception handler first,    # to get the standard error response.    response = exception_handler(exc, context)    # Now add the HTTP status code to the response.    if response is not None and response.status_code == 404:        response.data = {              "message": "Instance not found.",              "error": "HTTP_404_NOT_FOUND",          }    return response要为您的项目应用此处理程序,请将其添加到REST_FRAMEWORK设置中:REST_FRAMEWORK = {    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python