zoukankan      html  css  js  c++  java
  • 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={})
    
  • 相关阅读:
    mingw-gcc-10.0.1-experimental-i686-posix-sjlj-20200202-0303907
    可以修改 QtScrcpy 窗口大小的小工具
    autosub 添加代理服务器参数 -P --proxy
    Python网络数据采集系列-------概述
    【刷题笔记】I'm stuck! (迷宫)-----java方案
    【刷题笔记】火车购票-----java方案
    mvc自定义全局异常处理
    使用html2canvas实现浏览器截图
    再谈Newtonsoft.Json高级用法
    Spire.Doc组件读取与写入Word
  • 原文地址:https://www.cnblogs.com/h1227/p/13332627.html
Copyright © 2011-2022 走看看