首页 > 其他分享 >1. DRF 异常处理

1. DRF 异常处理

时间:2024-07-15 15:54:01浏览次数:9  
标签:code exc 处理 rest framework exceptions import 异常 DRF

目录

Django DRF 异常处理

1. DRF对异常(Exception)的处理源码

request请求先进到APIView的dispatch方法, 如果有异常走到exception。

2. 自定义异常返回

utils/handlers.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.views import set_rollback


def exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
        exc.ret_code = 1001
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
        exc.ret_code = 1002
    elif isinstance(exc, (AuthenticationFailed, NotAuthenticated)):
        exc.ret_code = 1003
    elif isinstance(exc, Throttled):
        exc.ret_code = 1004
    elif isinstance(exc, ValidationError):
        exc.ret_code = 1005

    # 只处理drf相关的异常
    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:
            code = getattr(exc, 'ret_code', None) or -1
            data = {'code': code, 'detail': exc.detail}

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

utils/exceptions.py

from rest_framework import exceptions

class ExtraException(exceptions.APIException):

def __init__(self, detail=None, ret_code=None, code=None):
    super().__init__(detail, code)
    self.ret_code = ret_code

views.py

from rest_framework import exceptions
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.throttling import BaseThrottle

from api import models
from utils.exceptions import ExtraException


class ExtraAuthentication(BaseAuthentication):
    def authenticate(self, request):
        raise exceptions.AuthenticationFailed("认证失败")

    def authenticate_header(self, request):
        return "api"


class ExtraPermission(BasePermission):
    def has_permission(self, request, view):
        return False

    def has_object_permission(self, request, view, obj):
        return False


class ExtraThrottle(BaseThrottle):
    def allow_request(self, request, view):
        return False


class DemoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"


class DemoView(ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin,
               GenericViewSet):
    # authentication_classes = [ExtraAuthentication]
    # throttle_classes = [ExtraThrottle]
    # permission_classes = [ExtraPermission]
    queryset = models.UserInfo.objects.all()
    serializer_class = DemoSerializer

    def perform_create(self, serializer):
        self.dispatch
        if True:
            # 自定义错误
            # raise ExtraException("数据异常")
            raise ExtraException("更新失败", ret_code=9000)
        serializer.save()

    def finalize_response(self, request, response, *args, **kwargs):
        response = super().finalize_response(request, response, *args, **kwargs)
        if response.exception:
            return response

        response.data = {'code': 0, 'data': response.data}
        return response

标签:code,exc,处理,rest,framework,exceptions,import,异常,DRF
From: https://www.cnblogs.com/khalil12138/p/18303313

相关文章

  • 【vue深入学习第2章】Vue.js 中的 Ajax 处理:vue-resource 库的深度解析
    Vue.js中的Ajax处理:vue-resource库的深度解析在现代前端开发中,Ajax请求是与后端进行数据交互的关键技术。Vue.js作为一个渐进式JavaScript框架,提供了多种方式来处理Ajax请求,其中vue-resource是一个较为常用的库。尽管vue-resource在Vue2.x之后不再是官方推荐的......
  • Java:什么是异常?一篇让你明白异常
    目录1.什么是异常?2.为什么需要异常处理3.异常处理的类型  3.1try-catch方式  3.2处理多种异常  3.3异常捕获的原理 3.4 异常处理的方式throws4.Exception下常用的api方法5.finally关键字6.throw关键字7.自定义异常1.什么是异常?异常就是程序在运行......
  • htmlToPdf处理视频
    一个写好的html页面要打印pdf,其中有视频也有图片。参考了网上的一些方法,最终是在获取数据的时候,对视频进行了截取第一帧处理。getFirstImgBase64(){this.piclist.forEach(item=>{if(item.url.endsWith('.mp4')){letdataURL=""letvideo=document.......
  • Panda数据处理
    一、Pandas简介Pandas,python+data+analysis的组合缩写,是python中基于numpy和matplotlib第三方数据分析库,与后者共同构成python数据分析基础工具包,享有数据三剑客之名。正因为pandas是在numpy基础上实现的,其核心数据结构与numpy的ndarray十分相似,但pandas与numpy的关系不是替代,而......
  • 关于 Scanner 类读取输入时换行符处理及不同方法的差异总结
    Scannerscanner=newScanner(System.in);System.out.print("请输入一个整数:");intnum=scanner.nextInt();System.out.print("请输入一个字符串:");Stringstr=scanner.nextLine();请输入一个整数:5......
  • Java中的异常
    异常概述:指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止。异常(Exception)的分类:编译时期异常:checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如期格式化异常)运行时期异常:runtime异常。在运行时期,检查异常.在编译时期,......
  • python库(13):Tablib库简化数据处理
    1 Tablib简介数据处理是一个常见且重要的任务。无论是数据科学、机器学习,还是日常数据分析,都需要处理和管理大量的数据。然而,标准库中的工具有时显得不够直观和简便。这时,我们可以借助第三方库来简化数据处理流程。Tablib就是这样一个强大的数据处理库,它提供了一套简单易用......
  • 【c语言】你绝对没见过的预处理技巧
    ......
  • OpenCV图像处理——霍夫圆检测与最小二乘法拟合圆
    HoughCircles:霍夫圆检测voidHoughCircles(InputArrayimage,OutputArraycircles,intmethod,doubledp,doubleminDist,doubleparam1=100,doubleparam2=100,intminRadius=0,intmaxRadius=0);image:输入,8-bit单通道灰度图circles:输出,vector,含有3或......
  • OpenCV图像处理——判断轮廓是否在圆环内
    要判断一个轮廓是否在圆环内,可以将问题分解为两个步骤:确保轮廓的所有点都在外圆内。确保轮廓的所有点都在内圆外。下面是一个完整的示例代码,展示如何实现这一点:#include<opencv2/opencv.hpp>#include<iostream>#include<vector>#include<cmath>usingnamespace......