zoukankan      html  css  js  c++  java
  • 07 drf过滤,排序与异常处理

    一.过滤

    ps:这里需要用到django-filter模块

    #1 安装:pip3 install django-filter
    #2 注册,在app中注册
    #3 全局配,或者局部配
     'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
    #4 视图类
    class BookView(ListAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
        filter_fields = ('age',)  #配置可以按照哪个字段来过滤
    

    二.排序

    # 局部使用
    from rest_framework.generics import ListAPIView
    from rest_framework.filters import OrderingFilter
    from app01.models import Book
    from app01.ser import BookSerializer
    class Book2View(ListAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
        filter_backends = [OrderingFilter]
        ordering_fields = ('id', 'price')
        
    # urls.py
    path('books2/', views.Book2View.as_view()),
    ]
    
    # 使用:
    http://127.0.0.1:8000/books2/?ordering=-price
    http://127.0.0.1:8000/books2/?ordering=price
    http://127.0.0.1:8000/books2/?ordering=-id
    

    三.异常处理

    #统一接口返回
    # 自定义异常方法,替换掉全局
    # 写一个方法
    # 自定义异常处理的方法
    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':999,'msg':str(exc)},status=status.HTTP_400_BAD_REQUEST)
        else:
            # return response
            return Response(data={'status':888,'msg':response.data.get('detail')},status=status.HTTP_400_BAD_REQUEST)
        
    # 全局配置setting.py
    'EXCEPTION_HANDLER': 'app01.app_auth.my_exception_handler',
    

    3.1封装一个Response对象

    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":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee')
    return APIResponse(data={"name":'lqz'})
    return APIResponse(code='101',msg='错误',data={"name":'lqz'},token='dsafsdfa',aa='dsafdsafasfdee',header={})
    

    3.2 REST framework里定义好的异常

    • APIException 所有异常的父类
    • ParseError 解析错误
    • AuthenticationFailed 认证失败
    • NotAuthenticated 尚未认证
    • PermissionDenied 权限决绝
    • NotFound 未找到
    • MethodNotAllowed 请求方式不支持
    • NotAcceptable 要获取的数据格式不支持
    • Throttled 超过限流次数
    • ValidationError 校验失败

    ps:如果没有定义好的异常,drf会直接return一个none,交给江狗来处理。

  • 相关阅读:
    梦断代码读后感一
    二阶段之五
    二柱子阶段二
    动手动脑
    二柱子
    开学测试
    jdk的安装
    软工人8月30日学习记录
    软工人8月29日学习记录
    软工人8月28日学习记录
  • 原文地址:https://www.cnblogs.com/bailongcaptain/p/13279481.html
Copyright © 2011-2022 走看看