Loading

后端返回值统一处理

1.使用示例
from utils.view import BaseView

class VideoView(BaseView, ModelViewSet):
    # ...
    # return Response({"code": 0, "data": context})
    return Response("放data对应的数据")

2.源码

utils下的view.py

from django.http import Http404

from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.exceptions import Throttled
from rest_framework.exceptions import PermissionDenied
from rest_framework.exceptions import NotAuthenticated
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.exceptions import PermissionDenied
from rest_framework.views import set_rollback
from rest_framework.exceptions import APIException

from rest_framework import status


class BaseView:
    def finalize_response(self, request, response, *args, **kwargs):
        response = super().finalize_response(request, response, *args, **kwargs)
        # 1.非正常
        if response.exception:
            return response
        # 2.正常
        response.data = {"code": 0, "data": response.data}
        response.status_code = status.HTTP_200_OK
        return response


def exception_handler(exc, context):
    if isinstance(exc, ValidationError):
        # 表单校验错误
        exc.ret_code = 2001
        exc.status_code = status.HTTP_200_OK
    elif isinstance(exc, AuthenticationFailed):
        # 认证失败
        exc.ret_code = 2002
        exc.status_code = status.HTTP_200_OK
    elif isinstance(exc, PermissionDenied):
        # 无权访问
        exc.ret_code = 2003
        exc.status_code = status.HTTP_200_OK
    elif isinstance(exc, Http404):
        exc.ret_code = 3001
        exc.status_code = status.HTTP_200_OK

    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

        exc_code = getattr(exc, 'ret_code', None) or -1
        data = {'code': exc_code, 'detail': exc.detail}

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

    # return None
    data = {'code': -1, 'detail': str(exc)}
    return Response(data, status=500)

对于exception_handler要在settings.py中引入

REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "UNAUTHENTICATED_TOKEN": None,
    "DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.RbacAuthentication"],
    "DEFAULT_PERMISSION_CLASSES": ["utils.permission.RbacPermission"],
    "EXCEPTION_HANDLER": "utils.view.exception_handler"
}
posted @ 2024-09-17 00:51  一只大学生  阅读(2)  评论(0编辑  收藏  举报