• drf自定义异常与封装response对象


    1 异常处理

    REST framework提供了异常处理,我们可以自定义异常处理函数。

    #统一接口返回
    
    # 自定义异常方法,替换掉全局
    # 写一个方法
    # 自定义异常处理的方法
    from rest_framework.views import exception_handler
    from rest_framework.response import Response
    from rest_framework import status
    # 自定义异常处理的方法
    def my_exception_handler(exc, context):
        response = exception_handler(exc, context)
        # 两种情况,一个是None,drf没有处理
        # response对象,django处理了,但是处理的不符合咱们的要求
        # print(type(exc))
    
        if not response:
            if isinstance(exc, ZeroDivisionError):
                return Response(data={'status': 777, 'msg': '除以0错误' + str(exc)}, status=status.HTTP_400_BAD_REQUEST)
            return Response(data={'status': 888, 'msg': str(exc)}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(data={'status': 999, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)
        
    # 全局配置setting.py
    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'app01.res.my_exception_handler',
    }
    
    # 如果未声明,会采用默认的方式,如下
    rest_frame/settings.py
    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    }
    

    1.1 REST framework定义的异常

    REST framework定义的异常
    APIException 所有异常的父类
    ParseError 解析错误
    AuthenticationFailed 认证失败
    NotAuthenticated 尚未认证
    PermissionDenied 权限决绝
    NotFound 未找到
    MethodNotAllowed 请求方式不支持
    NotAcceptable 要获取的数据格式不支持
    Throttled 超过限流次数
    ValidationError 校验失败
    也就是说,很多的没有在上面列出来的异常,就需要我们在自定义异常中自己处理了。
    

    2 封装Response对象

    from rest_framework.response import Response
    from rest_framework import status
    class APIResponse(Response):
        def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, **kwargs):
            dic = {'code': code, 'msg': msg}
            if data:
                dic = {'code': code, 'msg': msg, 'data': data}
            dic.update(kwargs)
            super().__init__(data=dic, status=status, headers=headers)
    # 使用
    return APIResponse(data={"name":'hjj'},token='asdasvg',aa='dasggasd')
    return APIResponse(data={"name":'hjj'})
    return APIResponse(code='101',msg='错误',data={"name":'hjj'},token='dsafsdfa',aa='dsafdsafasfdee',header={})
    
  • 相关阅读:
    【心情】一天又一天
    【转】深度学习目标检测的整体架构描述(one-stage/two-stage/multi-stage)
    如何转载CSDN以及博客园的文章
    【转】Faster RCNN原理分析(二):Region Proposal Networks详解
    Lintcode 627
    遇黑中介打官司拿到房租的成功案例
    记录音视频不同步的问题及解决过程
    ffmpeg 使用笔记
    centos min安装后使用gclient
    剑指 Offer 26. 树的子结构
  • 原文地址:https://www.cnblogs.com/h1227/p/13332627.html
Copyright © 2020-2023  润新知